Reference library

API design & gRPC

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

59 matches
API design & gRPC medium

How to Implement ETag Optimistic Concurrency in Python

Build a lightweight in-memory resource store that uses MD5 hash ETags to prevent lost updates via optimistic concurrency control.

etag concurrency hashing
Python
import hashlib
import json

class ResourceStore:
    def __init__(self):
        self.data = {}
        self.etags = {}

    def get(self, resource_id):
        if resource_id not in self.data:
            return None, None
        return self.data[resource_id], self.etags[resource_id]

    def put(self, resource_id, …
12 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 RBAC Permission Checks with a Route Decorator in Python

Build a reusable Python decorator that checks a user's role against allowed roles and raises a custom PermissionError when access is denied.

decorator rbac permissions
Python
from functools import wraps
from enum import Enum

class Role(Enum):
    ADMIN = "admin"
    MODERATOR = "moderator"
    USER = "user"

class PermissionError(Exception):
    pass

def require_role(*allowed_roles):
    def decorator(func):
        @wraps(func)
        def wrapper(user_role, *args, **kwargs):
          …
12 0 Open
API design & gRPC easy

How to Implement Sparse Fieldsets in Python

A function that filters API responses by resource type, returning only requested fields plus IDs, as a sparse fieldset mock.

api jsonapi sparse-fieldsets
Python
from dataclasses import dataclass, field
from typing import Dict, List, Optional


@dataclass
class MockResponse:
    data: Dict[str, object] = field(default_factory=dict)
    included: List[Dict[str, object]] = field(default_factory=list)


def select_fields(
    data: Dict[str, object],
    sparse_fields: Optional[D…
11 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…
12 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 …
11 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…
14 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)
        …
10 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…
12 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)
…
12 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…
12 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…
14 0 Open
API design & gRPC easy

How to Mock a GraphQL Query Type in Python

Create a lightweight mock of a GraphQL Query type to simulate repository lookups without a server.

graphql mock resolver
Python
import json

class Query:
    def __init__(self):
        self.starred_repos = [
            {"id": 1, "name": "graphql", "owner": "graphql"}
        ]

    def repository(self, name):
        if name == "graphql":
            return {"id": 1, "name": "graphql", "stargazerCount": 85000}
        return None


if __name…
13 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…
14 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…
11 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)
    
   …
12 0 Open
API design & gRPC easy

How to Parse gRPC Request Data in Python

Build a beginner-friendly gRPC service handler that parses incoming protobuf messages into Python dictionaries and starts a simple gRPC server.

grpc protobuf api
Python
from google.protobuf import json_format
import grpc
from concurrent import futures
import time


class DataParsingService:
    def parse(self, request):
        return {
            "received_json": json_format.MessageToJson(request),
            "parsed_fields": {
                "name": request.name,
               …
13 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 …
12 0 Open
API design & gRPC easy

How to Prefix Python API URIs with a Version Slug

Build a versioned API endpoint by optionally adding a version prefix like v1 to the URL path using the stdlib urllib module.

api url urllib
Python
from urllib.parse import urlparse

BASE_URL = "https://api.example.com"

def build_uri(resource, version="v1"):
    """Mock a versioned API URI with an optional v1 prefix."""
    parsed = urlparse(BASE_URL)
    prefix = f"/{version}" if version else ""
    return f"{parsed.scheme}://{parsed.netloc}{prefix}/{resource.l…
11 0 Open
API design & gRPC easy

How to Propagate X-Request-ID in Python

Generate a unique request ID when one is missing and pass it through API calls for distributed tracing.

request-id tracing api
Python
import uuid


def generate_request_id() -> str:
    """Generate a unique request ID similar to X-Request-ID header."""
    return str(uuid.uuid4())


def propagate_request_id(request_id: str | None) -> str:
    """Return the request ID for propagation, generating one if missing."""
    if request_id:
        return re…
11 0 Open
API design & gRPC easy

How to Serialize a Dataclass to JSON in Python

Serialize a Python dataclass instance to JSON using asdict and json.dumps for API responses or mocks.

dataclass json serialization
Python
from dataclasses import dataclass, asdict
import json


@dataclass
class UserResponse:
    id: int
    name: str
    email: str
    active: bool = True


if __name__ == "__main__":
    response = UserResponse(id=42, name="Ada Lovelace", email="ada@example.com")
    print(json.dumps(asdict(response), indent=2))
12 0 Open
API design & gRPC easy

How to Validate Data in Python for Beginners

A beginner-friendly Python class for validating required fields, types, ranges, and allowed choices in dict payloads.

validation data api
Python
import json
from typing import Any, Dict, List, Optional, Union


class Validator:
    """A simple validate data helper designed for beginners."""

    def __init__(self, data: Union[Dict[str, Any], List[Any]]):
        self.data = data
        self.errors: Dict[str, str] = {}

    def validate_required(self, field: s…
12 0 Open
API design & gRPC easy

How to Validate JWT Claims (exp, iss, aud) in Python

This code demonstrates how to decode and validate a JWT's essential claims—expiration (exp), issuer (iss), and audience (aud)—using the PyJWT library, returning clear error messages for common validation failures.

jwt authentication security
Python
import jwt
from datetime import datetime, timezone, timedelta

SECRET = "mock-secret"

def validate_token(token, expected_iss, expected_aud):
    try:
        decoded = jwt.decode(
            token,
            SECRET,
            algorithms=["HS256"],
            options={"require": ["exp", "iss", "aud"]},
         …
11 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

  …
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.