Reference library

API design & gRPC

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

10 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

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 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 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 easy

How to Poll an Operation Status Endpoint in Python

Mock a polling endpoint in Python that simulates checking an async operation's status until it completes or times out.

polling api async
Python
import time
import random


def poll_status(url: str, timeout: float = 5.0) -> dict:
    """Mock a polling endpoint that eventually returns a completed status."""
    start = time.time()
    while time.time() - start < timeout:
        # Simulate delayed response
        time.sleep(0.2)
        # 80% chance to report …
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 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 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 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.