Reference library

API design & gRPC

REST best practices, protobuf, API versioning, and backward-compatible service contracts.

8 matches
API design & gRPC medium

Build a Bulk Array POST Mock Server in Python

Creates an HTTP mock server that accepts POST requests with a JSON array and returns incremental IDs for each item.

http-server mock-api rest
Python
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse

class MockHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        if urlparse(self.path).path != "/bulk":
            self.send_response(404)
            self.end_headers()
            return

        cont…
16 0 Open
API design & gRPC medium

Build a Mock REST API with PUT and GET in Python

A minimal mock REST server implementing idempotent PUT for resource replacement and GET for retrieval, built with Python's http.server module.

rest-api http-server mock
Python
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
from urllib.parse import urlparse

mock_db = {}

class MockAPIHandler(BaseHTTPRequestHandler):
    def do_PUT(self):
        parsed = urlparse(self.path)
        resource_id = parsed.path.strip("/").split("/")[-1]
        content_length = int(self.…
15 0 Open
API design & gRPC medium

How to Build Cursor Pagination with Next and Prev Tokens in Python

A minimal cursor pagination implementation that returns next and previous cursor tokens for navigating a dataset.

pagination cursor api
Python
from pprint import pprint


def make_cursor(page):
    return f"page:{page:04d}"


def parse_cursor(cursor):
    _, page = cursor.split(":", 1)
    return int(page)


def paginate(all_items, page_size, cursor=None):
    start = parse_cursor(cursor) if cursor else 0
    end = start + page_size
    items = all_items[sta…
15 0 Open
API design & gRPC medium

How to Build a Hypermedia Collection Resource in Python

Creates a paginated hypermedia collection resource with HATEOAS links and embedded items.

hateoas hal pagination
Python
import json
import math


class HypermediaCollection:
    """A mock hypermedia collection resource."""

    def __init__(self, items, base_url="/api/items"):
        self.items = items
        self.base_url = base_url

    def to_dict(self, page=1, per_page=3):
        total = len(self.items)
        pages = math.ceil…
14 0 Open
API design & gRPC medium

How to Build a Mock REST GET Endpoint Handler in Python

Create a lightweight mock REST GET server in Python using the standard library, with a dict-based route registry that maps paths to handler functions and returns JSON responses with proper HTTP status codes.

mock-server rest-api http
Python
from http.server import BaseHTTPRequestHandler, HTTPServer
import json

# Mock API handler registry
def handle_users():
    return {"status": "ok", "data": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}

def handle_products():
    return {"status": "ok", "data": [{"id": 101, "name": "Laptop", "price": 999.99}…
14 0 Open
API design & gRPC medium

How to Build an Idempotency-Key POST Handler in Python

Python HTTP server mock that accepts POST requests and deduplicates them using an Idempotency-Key header, returning the same response for repeated calls.

http-server idempotency api-mock
Python
import hashlib
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse


class MockAPI(BaseHTTPRequestHandler):
    responses = {}

    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(length).decode("utf-8")
…
14 0 Open
API design & gRPC medium

How to Implement Content Negotiation with JSON and XML in Python

Build an HTTP server that returns JSON or XML responses based on the client's Accept header, with a 406 response for unsupported formats.

http-server content-negotiation json
Python
import json
import xml.etree.ElementTree as ET
from http.server import BaseHTTPRequestHandler, HTTPServer


class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        data = {"message": "Hello, world!"}
        accept_header = self.headers.get("Accept", "")

        if "application/json" in accept_hea…
11 0 Open
API design & gRPC medium

Implement If-Match Precondition Update in Python

A mock resource store that uses the If-Match header's ETag to guard updates, preventing overwrites from stale clients.

api etag optimistic-concurrency
Python
from dataclasses import dataclass
from typing import Optional


@dataclass
class Resource:
    id: str
    version: int = 1
    data: str = ""
    etag: str = "etag-1"


class MockResourceStore:
    def __init__(self):
        self.resources = {}

    def update(self, resource_id: str, new_data: str, if_match: Optiona…
13 0 Open

Browse by section

Each section groups closely related Python snippets.

API design & gRPC — Python code examples

What you will find here

This page collects api design & grpc snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

Samples vs tutorials and challenges

Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.