Blockchain 15 min read

Build a Simple Blockchain API with Python and Flask – Step‑by‑Step Guide

Learn how to build a functional blockchain in Python using Flask, covering environment setup, the core Blockchain class, block and transaction structures, a simple proof‑of‑work algorithm, RESTful API endpoints, node registration, and a longest‑chain consensus mechanism, complete with runnable code examples.

21CTO
21CTO
21CTO
Build a Simple Blockchain API with Python and Flask – Step‑by‑Step Guide

Environment Preparation

Ensure Python 3.6+, pip, Flask and requests are installed. Install specific versions with pip. pip install Flask==0.12.2 requests==2.18.4 Also need an HTTP client like Postman or cURL.

Blockchain Class

Define a Blockchain class that stores the chain and current transactions. The constructor creates the genesis block.

class Blockchain(object):
    def __init__(self):
        self.chain = []
        self.current_transactions = []
        self.new_block(previous_hash=1, proof=100)
    ...

Block Structure

Each block contains index, timestamp, transactions, proof and previous_hash.

block = {
    'index': 1,
    'timestamp': 1506057125.900785,
    'transactions': [{'sender': '8527147fe1f5426f9dd545de4b27ee00', 'recipient': 'a77f5cdfa2934df3954a5c7c7da5df1f', 'amount': 5}],
    'proof': 324984774000,
    'previous_hash': '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
}

Adding Transactions

The new_transaction method appends a transaction dictionary to self.current_transactions and returns the index of the block that will hold it.

def new_transaction(self, sender, recipient, amount):
    """Create a new transaction."""
    self.current_transactions.append({
        'sender': sender,
        'recipient': recipient,
        'amount': amount,
    })
    return self.last_block['index'] + 1

Proof of Work

Simple PoW searches for a number p such that hash(last_proof, p) starts with four zeros.

def proof_of_work(self, last_proof):
    proof = 0
    while not self.valid_proof(last_proof, proof):
        proof += 1
    return proof

@staticmethod
def valid_proof(last_proof, proof):
    guess = f'{last_proof}{proof}'.encode()
    guess_hash = hashlib.sha256(guess).hexdigest()
    return guess_hash[:4] == "0000"

Flask API

Expose three endpoints: /transactions/new (POST) to add a transaction, /mine (GET) to mine a new block, and /chain (GET) to return the full chain.

@app.route('/transactions/new', methods=['POST'])
def new_transaction():
    values = request.get_json()
    required = ['sender', 'recipient', 'amount']
    if not all(k in values for k in required):
        return 'Missing values', 400
    index = blockchain.new_transaction(values['sender'], values['recipient'], values['amount'])
    response = {'message': f'Transaction will be added to Block {index}'}
    return jsonify(response), 201

@app.route('/mine')
def mine():
    last_block = blockchain.last_block
    proof = blockchain.proof_of_work(last_block['proof'])
    blockchain.new_transaction(sender="0", recipient=node_identifier, amount=1)
    block = blockchain.new_block(proof)
    response = {
        'message': "New Block Forged",
        'index': block['index'],
        'transactions': block['transactions'],
        'proof': block['proof'],
        'previous_hash': block['previous_hash'],
    }
    return jsonify(response), 200

@app.route('/chain')
def full_chain():
    response = {'chain': blockchain.chain, 'length': len(blockchain.chain)}
    return jsonify(response), 200

Node Registration and Consensus

Nodes are stored in a set. The /nodes/register endpoint adds new node URLs, and /nodes/resolve runs the longest‑chain consensus algorithm.

def register_node(self, address):
    parsed_url = urlparse(address)
    self.nodes.add(parsed_url.netloc)

def resolve_conflicts(self):
    neighbours = self.nodes
    new_chain = None
    max_length = len(self.chain)
    for node in neighbours:
        response = requests.get(f'http://{node}/chain')
        if response.status_code == 200:
            length = response.json()['length']
            chain = response.json()['chain']
            if length > max_length and self.valid_chain(chain):
                max_length = length
                new_chain = chain
    if new_chain:
        self.chain = new_chain
        return True
    return False

Run the server with python blockchain.py and interact via cURL or Postman. Images illustrate mining output and node synchronization.

Mining output
Mining output
Transaction POST result
Transaction POST result
Node consensus result
Node consensus result
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonAPIFlaskConsensusProof of Work
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.