Skip to content

loryth-fastapi — Consumer Guide

Audience: Consumers — developers using loryth-fastapi in their services.

A library that extends FastAPI with additional functionality for building RESTful APIs.

Overview

The loryth-fastapi library provides extensions and utilities for the FastAPI framework, making it easier to build robust and consistent RESTful APIs in the Loryth ecosystem.

Key Components

API Status

  • ApiStatus: A set of standardized API status codes and messages for consistent API responses.

Custom Middleware

The library includes custom middleware components for FastAPI applications:

  • Authentication middleware
  • Request logging middleware
  • Error handling middleware
  • And more

Schema Definitions

The library provides schema definitions for API requests and responses, ensuring consistent API contracts:

  • Base request and response models
  • Pagination request and response models
  • Error response models
  • And more

Usage

To use the loryth-fastapi library, import the specific components you need:

from fastapi import FastAPI
from loryth.fastapi import ApiStatus
from loryth.fastapi.middleware import add_authentication_middleware

# Create a FastAPI application
app = FastAPI(title="My API")

# Add middleware
add_authentication_middleware(app)

# Define an endpoint
@app.get("/health")
def health_check():
    return {"status": ApiStatus.OK.value, "message": "Service is healthy"}

# Run the application
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Integration with Other Libraries

The loryth-fastapi library is designed to work seamlessly with other libraries in the Loryth ecosystem:

  • It uses loryth-common for common utilities and patterns.
  • It can integrate with loryth-domain for exposing domain functionality through APIs.
  • It can use loryth-persistence for data access in API handlers.
  • It can work with loryth-messages for implementing asynchronous API patterns.

Best Practices

When using the loryth-fastapi library, consider the following best practices:

  1. Use the provided middleware components for consistent behavior across APIs.
  2. Follow the standard response format for all API endpoints.
  3. Use the provided schema definitions for request and response models.
  4. Implement proper error handling using the provided error response models.
  5. Document your API endpoints using FastAPI's built-in documentation features.