Reference library

API design & gRPC

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

25 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…
15 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 easy

Generate an OpenAPI Spec from Mock Routes in Python

This Python script generates an OpenAPI 3.0 specification from a simple mock routes dictionary, mapping each HTTP method to response examples.

openapi api-docs api-design
Python
import json
from pathlib import Path


def generate_openapi_spec(routes: dict, title: str = "Mock API", version: str = "1.0.0") -> dict:
    paths = {}
    for route, methods in routes.items():
        path_item = {}
        for method, response_data in methods.items():
            method = method.lower()
            …
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 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 Handle Retry-After Header in Python

Parse the Retry-After header from rate-limited API responses and implement retry logic with proper delays in Python.

retry-after api rate-limiting
Python
```python
import time
from datetime import datetime, timedelta


class RetryAfterHandler:
    def __init__(self, max_retries=3):
        self.max_retries = max_retries

    def get_retry_after_seconds(self, response_headers):
        retry_after_value = response_headers.get("Retry-After")
        if retry_after_value …
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 easy

How to Implement Pagination with Offset and Limit in Python

A mock API pagination pattern that parses page and per_page query parameters, computes offset and limit, and slices a list of items for a specific page.

api pagination query-params
Python
def paginate(items, page, per_page):
    offset = (page - 1) * per_page
    return items[offset:offset + per_page]


def parse_query_params(query_string):
    params = {}
    if query_string:
        for pair in query_string.split("&"):
            key, value = pair.split("=")
            params[key] = value
    page …
12 0 Open
API design & gRPC easy

How to Implement a PATCH Partial Update Merge Dict in Python

Implements a recursive merge function that applies HTTP PATCH-like partial updates to a nested dictionary while preserving untouched fields.

http rest dict-merge
Python
import json

def patch_merge(target: dict, patch: dict) -> dict:
    """Simulate HTTP PATCH semantic: shallow-merge patch into a copy of target."""
    merged = target.copy()
    for key, value in patch.items():
        if isinstance(value, dict) and isinstance(merged.get(key), dict):
            merged[key] = patch_m…
13 0 Open
API design & gRPC easy

How to Implement a REST DELETE Mock Server Returning 204 in Python

A minimal HTTP server mock that responds to DELETE requests with 204, 404, or 403 statuses based on the resource ID.

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

class MockHandler(BaseHTTPRequestHandler):
    def do_DELETE(self):
        if self.path.startswith("/api/resource/"):
            resource_id = self.path.split("/")[-1]
            if resource_id == "42":
                # Successful delete: 204 …
12 0 Open
API design & gRPC easy

How to Mock Content-Disposition and Extract Filename in Python

Parse and mock Content-Disposition headers in Python to extract filenames, handling both plain and RFC 5987 encoded values.

http mocking regex
Python
import os
from pathlib import Path
import re
from unittest.mock import patch

def get_filename_from_content_disposition(header_value):
    """
    Extract filename from a Content-Disposition header value.
    Supports both filename and filename* parameters (RFC 5987).
    """
    if not header_value:
        return No…
15 0 Open
API design & gRPC easy

How to Mock HTTP 304 Responses with If-None-Match in Python

Spin up a local HTTP server that returns a 304 Not Modified when a request carries a matching ETag, useful for testing cache behavior.

http caching mock-server
Python
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
import urllib.request

ETAG = '"abc123"'
BODY = b'{"status": "ok"}'

class MockServer(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.headers.get('If-None-Match') == ETAG:
            self.send_response(304)
        …
11 0 Open
API design & gRPC medium

How to Mock X-RateLimit Headers in Python

This code creates a local HTTP server that mimics rate limit headers (X-RateLimit-Limit, Remaining, Reset, Update) and returns 429 responses when the limit is exceeded.

http rate-limit server
Python
import time
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer


class RateLimitHandler(BaseHTTPRequestHandler):
    RATE_LIMIT = 5          # max requests allowed
    WINDOW_SECONDS = 60     # per time window

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
…
14 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 Mock a Chunked Encoding Streaming Response in Python

Build a local mock HTTP server with Python's http.server that streams a chunked-encoded response with a 0.5s delay per chunk.

http streaming chunked
Python
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import time

class ChunkedHandler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-Type", "text/plain")
        self.send_header("Transfer-Encoding", "c…
15 0 Open
API design & gRPC medium

How to Mock a Webhook Subscribe Callback URL in Python

Mock a webhook subscribe callback URL using Python's http.server to receive and parse POST requests sent by webhook providers.

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

class WebhookHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers.get('Content-Length', 0))
        payload = json.loads(self.rfile.read(content_length)) if content_length else {}
        
        print…
15 0 Open
API design & gRPC easy

How to Mock an API Key Header Authentication Server in Python

A minimal HTTP server that validates requests using an X-API-Key header and returns JSON responses for authenticated and unauthenticated calls.

api authentication http
Python
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

API_KEYS = {"test-user": "secret-key-123"}

class AuthHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        auth = self.headers.get("X-API-Key")
        if not auth or auth not in API_KEYS.values():
            self.send_response…
12 0 Open
API design & gRPC medium

How to Parse Multipart Form Data in Python

Parse multipart/form-data uploads using the Python standard library's cgi module to extract both regular fields and file uploads.

multipart cgi form-data
Python
import cgi
from io import BytesIO

def parse_multipart_form(headers, body_bytes):
    content_type = headers.get("Content-Type", "")
    content_length = int(headers.get("Content-Length", len(body_bytes)))
    
    # Create a file-like object from bytes for cgi.FieldStorage
    body_file = BytesIO(body_bytes)
    
   …
13 0 Open
API design & gRPC easy

How to handle CORS preflight OPTIONS requests in Python

Create a mock HTTP server with a CORS preflight OPTIONS handler that returns the correct headers for browser-based API requests.

cors http server
Python
from http.server import BaseHTTPRequestHandler, HTTPServer

class CORSRequestHandler(BaseHTTPRequestHandler):
    def _send_cors_headers(self):
        self.send_header("Access-Control-Allow-Origin", "*")
        self.send_header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
        self.send_head…
13 0 Open
API design & gRPC medium

How to mock Server-Sent Events (SSE) in Python

A minimal HTTP server that streams Server-Sent Events to clients, perfect for testing and development.

sse server-sent-events http
Python
from http.server import HTTPServer, BaseHTTPRequestHandler
import threading
import time

MESSAGES = iter([
    "data: Hello world\n\n",
    "data: Second message\n\n",
    "event: custom\n",
    "data: Custom event payload\n\n",
    "data: Final message\n\n"
])

class SSEHandler(BaseHTTPRequestHandler):
    def do_GET…
14 0 Open
API design & gRPC easy

How to mock a REST POST endpoint in Python

Create a simple mock REST server that responds to POST requests with a 201 status and a JSON body.

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


class MockHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers.get("Content-Length", 0))
        body = self.rfile.read(content_length) if content_length else b"{}"
        try:
            data = json…
12 0 Open
API design & gRPC easy

Return Proper HTTP Status Codes Table in Python

Mock HTTP status code table with proper numeric and textual representations, including formatted status lines and a filtered table view.

http-status api mock
Python
# Mock HTTP status code table with proper numeric and textual representations

codes = {
    200: "OK",
    201: "Created",
    204: "No Content",
    301: "Moved Permanently",
    302: "Found",
    304: "Not Modified",
    400: "Bad Request",
    401: "Unauthorized",
    403: "Forbidden",
    404: "Not Found",
    50…
13 0 Open
API design & gRPC easy

Serve Swagger UI with Python's built-in HTTP server

Hosts a self-contained Swagger UI with a mock OpenAPI spec using only Python's standard library HTTP server.

swagger openapi http-server
Python
from http.server import HTTPServer, SimpleHTTPRequestHandler
import os
import tempfile

SWAGGER_HTML = """<!DOCTYPE html>
<html>
<head>
    <title>Mock Swagger UI</title>
    <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@4/swagger-ui.css">
</head>
<body>
    <div id="swagger-ui"></div>
    <script src…
14 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.