Reference library

API design & gRPC

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

6 matches
API design & gRPC easy

How to Decode Basic Auth Credentials in Python

Decode username and password from a Basic Auth header string using base64 and standard string operations.

base64 authentication api
Python
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…
13 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…
13 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…
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"]},
         …
12 0 Open
API design & gRPC easy

How to Validate a JWT Signature in Python with a Mock Secret

Validates a JWT's signature using a mock secret, decoding and handling expired or invalid tokens gracefully.

jwt authentication security
Python
import jwt
import time

SECRET = "mock_secret_key_123"

def validate_token(token):
    try:
        payload = jwt.decode(token, SECRET, algorithms=["HS256"])
        return f"Valid token. Payload: {payload}"
    except jwt.ExpiredSignatureError:
        return "Token expired"
    except jwt.InvalidTokenError:
        …
12 0 Open
API design & gRPC easy

Scope-based authorization in Python

A simple Python class that checks user scopes against required permissions for a resource, returning an authorization decision.

authorization scopes oauth
Python
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…
12 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.