API design & gRPC
REST best practices, protobuf, API versioning, and backward-compatible service contracts.
How to Add HATEOAS Links to a Python API Response
Build a Python API resource class that adds self and next HATEOAS links to JSON responses, with a mock example for pagination.
import json
class Resource:
def __init__(self, name, data, next_page=None):
self.links = {"self": f"/api/resources/{name}"}
if next_page is not None:
self.links["next"] = f"/api/resources?page={next_page}"
self.data = data
def to_dict(self):
return {"links": self.…
How to Add a Correlation ID Tracing Header in Python
A mock middleware generates or preserves a correlation ID header and logs structured JSON messages with it for API request tracing.
import uuid
import json
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Request:
headers: dict = field(default_factory=dict)
def get(self, key, default=None):
return self.headers.get(key, default)
class CorrelationIdMiddleware:
def __init__(self, header_name…
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.
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…
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.
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…
How to Build a Data Helper Class in Python for Beginners
Create a beginner-friendly DataHelper class that stores, retrieves, filters, and summarizes records in a list of dictionaries.
from __future__ import annotations
import json
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
@dataclass
class DataHelper:
"""A beginner-friendly helper for common data tasks."""
data: List[Dict[str, Any]] = field(default_factory=list)
def add_record(self, record…
How to Build a Hypermedia Collection Resource in Python
Creates a paginated hypermedia collection resource with HATEOAS links and embedded items.
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…
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.
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}…
How to Build a Simple Data Helper in Python for API Design
Create a beginner-friendly DataHelper class that demonstrates basic CRUD operations (add, get, list, remove) using an in-memory dictionary, ideal for learning API design concepts.
class DataHelper:
"""Simple data helper for beginners learning API design concepts."""
def __init__(self):
self._data = {}
def add_record(self, key, value):
"""Add a record to the store."""
self._data[key] = value
return f"Added: {key} -> {value}"
def get_…
How to Build a Simple Filter Helper in Python for API Design
Create a reusable data filter service with dataclasses that mimics gRPC request/response patterns for filtering dataset records.
from dataclasses import dataclass, field
from typing import List, Optional, Dict, Any
@dataclass
class FilterRequest:
"""A simple filter request mirroring a gRPC message structure."""
field_name: str
operator: str # eq, ne, gt, lt, contains
value: Any
page_size: int = 10
page_token: Optional…
How to Build a Simple gRPC-Style Data Service in Python
Create a beginner-friendly gRPC-style service with dataclasses to simulate GetUser and CreateUser RPCs.
from dataclasses import dataclass
from typing import Optional
@dataclass
class User:
id: int
name: str
email: str
class UserService:
"""Simple gRPC-style service contract for beginner learners."""
def get_user(self, user_id: int) -> Optional[User]:
"""Simulated gRPC GetUser RPC."""
…
How to Build a WebSocket Echo Server in Python with asyncio
Create a simple WebSocket echo server using the websockets library and asyncio to handle concurrent connections.
import asyncio
import websockets
async def echo(websocket):
async for message in websocket:
await websocket.send(f"Echo: {message}")
async def main():
async with websockets.serve(echo, "localhost", 8765):
print("WebSocket server started on ws://localhost:8765")
await asyncio.Future() …
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.
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")
…
How to Create an RFC 7807 Error JSON in Python
Construct a structured error response using the RFC 7807 Problem Details format with a reusable function.
import json
from typing import Dict
def create_rfc7807_error(
type_: str,
title: str,
status: int,
detail: str,
instance: str,
extra_fields: Dict[str, object] | None = None,
) -> str:
"""
Build a JSON string following RFC 7807 Problem Details format.
"""
problem = {
"t…
How to Decode Basic Auth Credentials in Python
Decode username and password from a Basic Auth header string using base64 and standard string operations.
import base64
def decode_basic_auth(header_value):
"""
Decode credentials from a Basic Auth header value.
Expected format: "Basic base64encoded(username:password)"
Returns a tuple (username, password).
"""
if not header_value.startswith("Basic "):
raise ValueError("Invalid Basic A…
How to Expand Related Resources with a Mock Embed in Python
Simulate API response embedding by attaching mock embedded data to each related resource in a list using a simple Python class.
import json
class EmbedMock:
def __init__(self, resources):
self.resources = resources
def expand(self):
for resource in self.resources:
resource["embedded"] = self._generate_embed()
def _generate_embed(self):
return {
"id": 1,
"type": "mock",
…
How to Filter Query Parameters by Operator in Python
Parse a URL query string and keep only parameters with allowed comparison operators like eq, gt, and lt.
from urllib.parse import urlparse, parse_qs
def filter_operators(query_string, allowed=("eq", "gt", "lt")):
parsed = urlparse(query_string)
params = parse_qs(parsed.query)
filtered = {}
for key, values in params.items():
if "__" in key:
field, op = key.rsplit("__", 1)
i…
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.
```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 …
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.
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…
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.
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, …
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.
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 …
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.
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):
…
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.
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…
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.
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…
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.
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 …
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.