API design & gRPC
REST best practices, protobuf, API versioning, and backward-compatible service contracts.
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 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.
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 …
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…
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.