Skip to content

XAPI Guard is FastAPI middleware that protects your API endpoints by validating the X-API-Key header. It's designed in a decorator style, so you can annotate your FastAPI endpoints with @guard.protect to protect them.

License

Notifications You must be signed in to change notification settings

anqorithm/xapi_guard_middleware

Repository files navigation

XAPI Guard Middleware

ZLoggerKit Logo

Downloads PyPI version License: MIT XAPI Guard Python FastAPI Code style: black Tests Coverage

XAPI Guard is FastAPI middleware that protects your API endpoints by validating the X-API-Key header. It's designed in a decorator style, so you can annotate your FastAPI endpoints with @guard.protect to protect them.

Features

  • Protect your FastAPI endpoints by validating the X-API-Key header.
  • Use @guard.protect to secure specific routes or entire routers.
  • Easily configure which routes require protection and which are public.
  • Automatically handle unauthorized access with appropriate error messages.
  • Support for OpenAPI/Swagger documentation with protected routes.

Installation

Choose your preferred installation method:

Poetry (Recommended)

poetry add xapi-guard-middleware

Pip

pip install xapi-guard-middleware

Quick Start

Generating a Secure API Key

For security best practices, XAPI Guard recommends using 128-bit API keys with mixed letters and numbers. You can generate a secure API key using one of these methods:

  1. Using the recommended online generator:

  2. Using Python's secrets module (recommended for production):

import secrets
import string


def generate_api_key(length=64):
    alphabet = string.ascii_letters + string.digits
    key = "".join(secrets.choice(alphabet) for _ in range(length))
    return f"sk_{key}"


api_key = generate_api_key()
print(api_key)

You can run this script from scripts/generator.py:

python3 scripts/generator.py
# Output: sk_mpo0ad7e4AlqYyinUZenCaXlerWr48aG30kgjGeXxFrEvH895C2qUtISBLIgc1Ek

Example API key format:

sk_mpo0ad7e4AlqYyinUZenCaXlerWr48aG30kgjGeXxFrEvH895C2qUtISBLIgc1Ek

Security Tips:

  • Always use 128-bit or longer keys for production environments
  • Avoid using special characters to ensure compatibility across different systems
  • Store API keys securely and never commit them to version control
  • Rotate API keys periodically for enhanced security
from fastapi import FastAPI, Depends, APIRouter
from xapi_guard_middleware import XAPIGuardMiddleware

app = FastAPI(title="XAPI Guard Middleware Example")

guard = XAPIGuardMiddleware(x_api_key="sk_85BnHrWHbLEKty7gNXVSwP385eLZipN6UvlSRjcvOXucwWq7MqAmvB5PhQ5xhy5n0uVFxluUuomCzRpoNuL7ffEnMApAs9hwIUDtoWN1je9ZYIkqAz6qrVSWdbZs8")

# Routers for different route groups
admin_router = APIRouter(dependencies=[Depends(guard.protect)])
settings_router = APIRouter(dependencies=[Depends(guard.protect)])
public_router = APIRouter()

# General routes
@app.get("/", tags=["General"])
async def root():
    """Root endpoint returning a welcome message."""
    return {"message": "Hello World"}


@app.get("/health", tags=["General"])
async def health():
    """Health check endpoint to verify service status."""
    return {"status": "healthy"}


# Public routes
@public_router.get("/public", tags=["Public"])
async def public():
    """Public endpoint accessible to everyone."""
    return {"message": "This is a public endpoint accessible to everyone."}


# Admin routes
@admin_router.get("/admin", tags=["Admin"])
async def admin():
    """Admin area endpoint."""
    return {"message": "Welcome to the admin area!"}


# Settings routes
@settings_router.get("/settings", tags=["Settings"])
async def settings():
    """Settings page, accessible only to authorized users."""
    return {"message": "Settings page, accessible only to authorized users."}


# Include the routers in the main app
app.include_router(public_router)
app.include_router(admin_router, prefix="/secure")
app.include_router(settings_router, prefix="/secure")

Demo

Running the FastAPI app

$ poetry install

$ poetry shell

$ poetry run uvicorn examples.app:app --reload

Making Requests

# Unauthorized request (invalid API key)
curl -X GET http://localhost:8000/secure/admin -H "X-API-Key: wrong-key"
# {
#   "detail": {
#     "code": "INVALID_API_KEY",
#     "message": "Invalid API key"
#   }
# }
# Status code: 403

# Authorized request
curl -X GET http://localhost:8000/secure/admin -H "X-API-Key: YOUR_API_KEY"
# Response: {"message": "Welcome to the admin area!"}
# Status code: 200
  • The FastAPI app is protected by the XAPI Guard Middleware image

  • X-API-Key header is missing image

  • X-API-Key header is invalid image image

  • X-API-Key header is valid image image

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

Contributors

License

This project is licensed under the MIT License. See the LICENSE file for details.

About

XAPI Guard is FastAPI middleware that protects your API endpoints by validating the X-API-Key header. It's designed in a decorator style, so you can annotate your FastAPI endpoints with @guard.protect to protect them.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages