Reference library

API design & gRPC

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

10 matches
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 Batch Operations Multi-Status 207 Mock Server in Python

Build a mock HTTP server that accepts a batch of operations and returns HTTP 207 Multi-Status with per-operation status codes in JSON.

http-server batch multi-status
Python
from http.server import BaseHTTPRequestHandler, HTTPServer
import json

class BatchHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path != "/batch":
            self.send_response(404)
            self.end_headers()
            return

        content_length = int(self.headers.get("Content-Leng…
13 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 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

How to Mock OAuth2 Bearer Token Auth Middleware in Python

Create a simple OAuth2 bearer token authentication middleware that verifies signed tokens and enforces scope-based access control.

oauth2 security middleware
Python
import hmac
import time
import base64
import json
from functools import wraps

VALID_TOKENS = {"test_token_123": {"user": "alice", "scope": "read:posts"}}


def generate_token(username: str) -> str:
    payload = {"user": username, "iat": int(time.time())}
    encoded = base64.urlsafe_b64encode(json.dumps(payload).enc…
13 0 Open
API design & gRPC medium

How to Mock a 202 Accepted Long-Running Operation in Python

Build a mock HTTP server that returns a 202 Accepted response immediately and simulates a long-running operation in the background with threading.

api mock-server http
Python
import time
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler

class MockHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        if self.path == "/long-running":
            self.send_response(202)
            self.send_header("Content-Type", "application/json")
            self.end_h…
13 0 Open
API design & gRPC medium

How to Validate Request Body JSON Against a Schema in Python

Build a lightweight schema validator to check required fields, types, string lengths, allowed values, and nested objects in a JSON request body.

api-validation json schema-validation
Python
import json


def validate_against_schema(data, schema, path=""):
    errors = []

    if not isinstance(data, dict):
        errors.append(f"{path}: expected object, got {type(data).__name__}")
        return errors

    for field, rules in schema.items():
        field_path = f"{path}.{field}" if path else field

  …
15 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
API design & gRPC medium

Version API by Accept Header with Vendor Media Types in Python

Build a mock HTTP server that routes to API versions by parsing vendor-specific Accept headers in Python.

api-versioning accept-header http-server
Python
from http.client import HTTPMessage
from http.server import BaseHTTPRequestHandler, HTTPServer


class VendorVersionHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        accept = self.headers.get("Accept", "")
        version = "v1"
        if "application/vnd.myapi.v2+json" in accept:
            version = "…
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.