API design & gRPC
REST best practices, protobuf, API versioning, and backward-compatible service contracts.
Convert Protobuf to JSON and Dict in Python
Provides static helper methods to convert between protobuf messages, JSON strings, and Python dictionaries using the google.protobuf library.
from google.protobuf.json_format import MessageToJson, Parse
import json
class DataConverter:
"""Helper class to convert between protobuf messages and common formats."""
@staticmethod
def to_json(message, indent=2):
"""Convert a protobuf message to JSON string."""
return MessageToJson(me…
Format data in Python using dataclasses like gRPC messages
Convert Python dataclasses to and from dicts and format them gRPC-style for clean data handling.
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
@dataclass
class ProductInfo:
"""Data class representing a gRPC-style product message."""
name: str
price: float
tags: List[str]
description: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
"""C…
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 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.
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,
…
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"]},
…
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.