API design & gRPC
REST best practices, protobuf, API versioning, and backward-compatible service contracts.
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 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 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.
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…
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.
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)
…
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.
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"]},
…
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.
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
…
Scope-based authorization in Python
A simple Python class that checks user scopes against required permissions for a resource, returning an authorization decision.
class ScopeAuthorization:
def __init__(self):
self.scopes = {
"read": ["resource:read"],
"write": ["resource:read", "resource:write"],
"admin": ["resource:read", "resource:write", "resource:delete"]
}
def authorize(self, user_scopes, required_scope, resource…
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.
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…
Verify Webhook HMAC Signatures in Python
Create and verify HMAC-SHA256 signatures for webhook payloads using Python's hmac module, protecting against tampering.
import hashlib
import hmac
import json
SECRET = b"super-secret-webhook-key"
def create_signature(payload: bytes) -> str:
return hmac.new(SECRET, payload, hashlib.sha256).hexdigest()
def verify_signature(payload: bytes, signature: str) -> bool:
expected = create_signature(payload)
return hmac.compare_dig…
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.