### FastOpenAPI Complete Example Setup Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/quart.md Basic setup for a FastOpenAPI application with Quart, including router initialization with API metadata. ```python from quart import Quart from pydantic import BaseModel, EmailStr from fastopenapi.routers import QuartRouter from fastopenapi.errors import ResourceNotFoundError from fastopenapi import Query app = Quart(__name__) router = QuartRouter( app=app, title="User Management API", version="1.0.0" ) ``` -------------------------------- ### Complete Example Setup Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/examples/file_uploads.md Initializes a Flask application and a FlaskRouter for the File Management API. ```python from flask import Flask from pydantic import BaseModel from datetime import datetime from fastopenapi import File, FileUpload, Form, Response from fastopenapi.routers import FlaskRouter from fastopenapi.errors import ResourceNotFoundError, BadRequestError import os import uuid app = Flask(__name__) router = FlaskRouter( app=app, title="File Management API", version="1.0.0" ) ``` -------------------------------- ### Setup Database Connection Pool on Server Start Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/sanic.md Use `@app.before_server_start` to initialize resources like database connection pools before the server begins accepting requests. ```python async def setup_db(app, loop): app.ctx.db = await create_db_pool() ``` -------------------------------- ### Basic Asynchronous Falcon (ASGI) Setup Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/falcon.md Set up a basic asynchronous Falcon application using FastOpenAPI's FalconAsyncRouter. This example shows an async API with root and item creation endpoints. ```python import falcon.asgi import uvicorn from pydantic import BaseModel from fastopenapi.routers import FalconAsyncRouter app = falcon.asgi.App() router = FalconAsyncRouter( app=app, title="Falcon Async API", version="1.0.0" ) class Item(BaseModel): name: str price: float @router.get("/") async def root(): return {"message": "Hello from async Falcon!"} @router.post("/items", response_model=Item, status_code=201) async def create_item(item: Item): return item if __name__ == "__main__": uvicorn.run(app, host="127.0.0.1", port=8000) ``` -------------------------------- ### Basic Synchronous Falcon (WSGI) Setup Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/falcon.md Set up a basic synchronous Falcon application using FastOpenAPI's FalconRouter. This example demonstrates defining a simple API with root and item creation endpoints. ```python import falcon from pydantic import BaseModel from fastopenapi.routers import FalconRouter app = falcon.App() router = FalconRouter( app=app, title="Falcon API", version="1.0.0" ) class Item(BaseModel): name: str price: float @router.get("/") def root(): return {"message": "Hello from Falcon!"} @router.post("/items", response_model=Item, status_code=201) def create_item(item: Item): return item if __name__ == "__main__": from wsgiref import simple_server httpd = simple_server.make_server('127.0.0.1', 8000, app) httpd.serve_forever() ``` -------------------------------- ### Add Descriptions and Examples to Query Parameters Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/guide/request_parameters.md Use the 'description' and 'example' arguments in Query to provide documentation and example values for parameters. ```python @router.get("/items") def list_items( search: str = Query( None, description="Search items by name or description", example="laptop" ), min_price: float = Query( 0, description="Minimum price filter", example=99.99 ) ): return {} ``` -------------------------------- ### Install FastOpenAPI with Tornado Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/README.md Install FastOpenAPI with support for the Tornado framework. ```bash pip install fastopenapi[tornado] ``` -------------------------------- ### Install Framework Separately for Troubleshooting Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/getting_started/installation.md Command to install a web framework (e.g., Flask) directly using pip, as an alternative to installing framework extras. ```bash pip install flask ``` -------------------------------- ### Upload File Examples Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/api_reference/types.md Examples showing how to handle file uploads using synchronous and asynchronous routes. ```python @router.post("/upload") def upload(file: FileUpload = File(...)): content = file.read() return {"size": len(content)} ``` ```python @router.post("/upload") async def upload(file: FileUpload = File(...)): content = await file.aread() return {"size": len(content)} ``` -------------------------------- ### Install FastOpenAPI with Quart Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/README.md Install FastOpenAPI with support for the Quart framework. ```bash pip install fastopenapi[quart] ``` -------------------------------- ### Basic Flask API Setup with FastOpenAPI Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/flask.md Initialize a Flask app and FastOpenAPI router, define a Pydantic model, and set up basic routes for GET and POST requests. ```python from flask import Flask from pydantic import BaseModel from fastopenapi.routers import FlaskRouter app = Flask(__name__) router = FlaskRouter( app=app, title="Flask API", version="1.0.0" ) class Item(BaseModel): name: str price: float @router.get("/") def root(): return {"message": "Hello from Flask!"} @router.post("/items", response_model=Item, status_code=201) def create_item(item: Item): return item if __name__ == "__main__": app.run(debug=True, port=8000) ``` -------------------------------- ### Install FastOpenAPI with Django Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/README.md Install FastOpenAPI with support for the Django framework. ```bash pip install fastopenapi[django] ``` -------------------------------- ### Install FastOpenAPI with Falcon Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/README.md Install FastOpenAPI with support for the Falcon framework. ```bash pip install fastopenapi[falcon] ``` -------------------------------- ### Install FastOpenAPI with Aiohttp Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/README.md Install FastOpenAPI with support for the aiohttp framework. ```bash pip install fastopenapi[aiohttp] ``` -------------------------------- ### Documenting Request Body Example Values Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/advanced/openapi_customization.md Provide example values for fields in the request body to guide users on the expected data format. ```APIDOC ### Request Body Documentation #### Example Values ```python class UserCreate(BaseModel): username: str = Field(..., example="johndoe") email: EmailStr = Field(..., example="john@example.com") age: int = Field(..., example=25, ge=0, le=120) @router.post("/users") def create_user(user: UserCreate): return user ``` ``` -------------------------------- ### Basic Tornado Setup Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/tornado.md Initialize a Tornado application with a FastOpenAPI router. ```python import asyncio from tornado.web import Application from pydantic import BaseModel from fastopenapi.routers import TornadoRouter app = Application() router = TornadoRouter( app=app, title="Tornado API", version="1.0.0" ) class Item(BaseModel): name: str price: float @router.get("/") async def root(): return {"message": "Hello from Tornado!"} @router.post("/items", response_model=Item, status_code=201) async def create_item(item: Item): return item async def main(): app.listen(8000) print("Server running on http://localhost:8000") await asyncio.Event().wait() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Provide Examples Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/guide/validation.md Adds example values to field definitions for better API documentation. ```python # Good email: EmailStr = Field( ..., description="User email", examples=["user@example.com"] ) ``` -------------------------------- ### Start Benchmark Implementations Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/benchmarks/README.md Commands to launch the various framework implementations for benchmarking. ```bash # Pure implementation (port 8000) python benchmarks//pure.py # With validators (port 8001) python benchmarks//with_validators.py # With FastOpenAPI (port 8002) python benchmarks//with_fastopenapi.py # FastAPI for comparison (port 8003) python benchmarks/fastapi/run.py ``` ```bash python benchmarks/aiohttp/pure.py python benchmarks/aiohttp/with_validators.py python benchmarks/aiohttp/with_fastopenapi.py python benchmarks/fastapi/run.py ``` -------------------------------- ### Install FastOpenAPI with Flask Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/README.md Install FastOpenAPI with support for the Flask framework. ```bash pip install fastopenapi[flask] ``` -------------------------------- ### Install FastOpenAPI with Starlette Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/README.md Install FastOpenAPI with support for the Starlette framework. ```bash pip install fastopenapi[starlette] ``` -------------------------------- ### Install FastOpenAPI with Sanic Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/README.md Install FastOpenAPI with support for the Sanic framework. ```bash pip install fastopenapi[sanic] ``` -------------------------------- ### Install FastOpenAPI with Framework Support Source: https://context7.com/mr-fatalyst/fastopenapi/llms.txt Install the base FastOpenAPI package or with specific framework integrations using pip. ```bash pip install fastopenapi ``` ```bash pip install fastopenapi[flask] ``` ```bash pip install fastopenapi[django] ``` ```bash pip install fastopenapi[starlette] ``` ```bash pip install fastopenapi[aiohttp] ``` ```bash pip install fastopenapi[falcon] ``` ```bash pip install fastopenapi[quart] ``` ```bash pip install fastopenapi[sanic] ``` ```bash pip install fastopenapi[tornado] ``` -------------------------------- ### Install FastOpenAPI with Multiple Frameworks Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/getting_started/installation.md Installs FastOpenAPI with support for multiple web frameworks simultaneously, useful for testing or library development. ```bash pip install fastopenapi[flask,starlette,django] ``` -------------------------------- ### Complete CRUD API Example with FastOpenAPI Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/examples/crud_api.md This comprehensive example sets up a Flask application with FastOpenAPI to manage users. It includes Pydantic models for request and response data, helper functions for password hashing and user lookups, and an in-memory database. Ensure Flask and Pydantic are installed. ```python import hashlib from datetime import datetime from flask import Flask from pydantic import BaseModel, EmailStr, Field from fastopenapi import Query from fastopenapi.errors import BadRequestError, ResourceNotFoundError from fastopenapi.routers import FlaskRouter app = Flask(__name__) router = FlaskRouter( app=app, title="User Management API", version="1.0.0", description="Complete CRUD API for user management", ) # In-memory database users_db: dict[int, dict] = {} next_id = 1 # Models class UserBase(BaseModel): username: str = Field(..., min_length=3, max_length=50) email: EmailStr full_name: str | None = Field(None, max_length=100) is_active: bool = True class UserCreate(UserBase): password: str = Field(..., min_length=8) class UserUpdate(BaseModel): username: str | None = Field(None, min_length=3, max_length=50) email: EmailStr | None = None full_name: str | None = Field(None, max_length=100) password: str | None = Field(None, min_length=8) is_active: bool | None = None class UserResponse(UserBase): id: int created_at: datetime updated_at: datetime class UserListResponse(BaseModel): users: list[UserResponse] total: int page: int per_page: int total_pages: int class BulkUserCreate(BaseModel): users: list[UserCreate] class BulkUserDelete(BaseModel): user_ids: list[int] class BulkResultResponse(BaseModel): success_count: int success_ids: list[int] error_count: int errors: list[dict] # Helpers def hash_password(password: str) -> str: """Simplified hash — use bcrypt in production.""" return hashlib.sha256(password.encode()).hexdigest() def find_user(username: str | None = None, email: str | None = None) -> dict | None: for user in users_db.values(): if username and user["username"] == username: return user if email and user["email"] == email: return user return None def user_response(user: dict) -> dict: """Strip internal fields before returning.""" return {k: v for k, v in user.items() if k != "password_hash"} def check_unique(username: str, email: str, exclude_id: int | None = None): existing = find_user(username=username) if existing and existing["id"] != exclude_id: raise BadRequestError(f"Username '{username}' already exists") existing = find_user(email=email) if existing and existing["id"] != exclude_id: raise BadRequestError(f"Email '{email}' already exists") ``` -------------------------------- ### FileUpload Usage and Async Examples Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/api_reference/types.md Complete examples for handling file uploads in Flask and Starlette routers. ```python from fastopenapi import File, FileUpload from fastopenapi.routers import FlaskRouter router = FlaskRouter() @router.post("/upload") def upload_file( file: FileUpload = File(..., description="File to upload") ): # Access file metadata print(f"Filename: {file.filename}") print(f"Content-Type: {file.content_type}") print(f"Size: {file.size} bytes") # Read file content content = file.read() # Process the file... return { "filename": file.filename, "size": file.size, "content_type": file.content_type } ``` ```python from fastopenapi.routers import StarletteRouter router = StarletteRouter() @router.post("/upload") async def upload_file(file: FileUpload = File(...)): content = await file.aread() # Save to disk with open(f"uploads/{file.filename}", "wb") as f: f.write(content) return {"filename": file.filename, "size": len(content)} ``` -------------------------------- ### Install FastOpenAPI Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/README.md Install only the core FastOpenAPI library using pip. ```bash pip install fastopenapi ``` -------------------------------- ### Development Installation of FastOpenAPI Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/getting_started/installation.md Installs FastOpenAPI in development mode with all extras, suitable for contributing to the project or running tests. Requires cloning the repository and using Poetry. ```bash git clone https://github.com/mr-fatalyst/fastopenapi.git cd fastopenapi poetry install --all-extras ``` -------------------------------- ### Benchmark Output Examples Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/benchmarks/README.md Examples of the output format generated by the benchmark suite. ```markdown ================================================================================ ## Framework Pure (round 1) Concurrency: **20** | Endpoint | RPS | Mean (ms) | p50 (ms) | p95 (ms) | p99 (ms) | Min (ms) | Max (ms) | |:---------|----:|----------:|---------:|---------:|---------:|---------:|---------:| | `GET all records` | 45230 | 2.21 | 2.10 | 3.50 | 4.80 | 1.20 | 8.50 | | `GET one record` | 46890 | 2.13 | 2.05 | 3.30 | 4.60 | 1.15 | 7.80 | | `POST new record` | 38450 | 2.60 | 2.45 | 4.10 | 5.90 | 1.40 | 10.20 | | `PUT record` | 42100 | 2.37 | 2.25 | 3.80 | 5.30 | 1.30 | 9.10 | | `PATCH record` | 43200 | 2.31 | 2.20 | 3.70 | 5.10 | 1.25 | 8.80 | | `DELETE record` | 41500 | 2.41 | 2.30 | 3.85 | 5.40 | 1.35 | 9.50 | ``` ```markdown ================================================================================ # SUMMARY: Median Results Across All Rounds ================================================================================ ## Framework Pure | Endpoint | RPS (median) | p95 (ms) | |:---------|-------------:|---------:| | `GET all records` | 45180 | 3.48 | | `GET one record` | 46820 | 3.28 | | `POST new record` | 38390 | 4.08 | | `PUT record` | 42050 | 3.78 | | `PATCH record` | 43150 | 3.68 | | `DELETE record` | 41450 | 3.82 | ## Framework + Validators | Endpoint | RPS (median) | p95 (ms) | |:---------|-------------:|---------:| | `GET all records` | 42300 | 3.75 | | `GET one record` | 43950 | 3.58 | ... ``` ```markdown ================================================================================ ## Framework — Performance Comparison (Pure = 100% baseline) ### Requests Per Second (higher is better) | Endpoint | Pure | +Validators | Δ% | +FastOpenAPI | Δ% | FastAPI | Δ% | |---------|-----:|------------:|---:|-------------:|---:|--------:|---:| | `GET all records` | 45180 | 42300 | -6.4% | 41200 | -8.8% | 40500 | -10.4% | | `GET one record` | 46820 | 43950 | -6.1% | 42800 | -8.6% | 41900 | -10.5% | | `POST new record` | 38390 | 35200 | -8.3% | 34100 | -11.2% | 33500 | -12.7% | ... ``` -------------------------------- ### GET /hello Source: https://context7.com/mr-fatalyst/fastopenapi/llms.txt Say hello from Tornado. ```APIDOC ## GET /hello ### Description Say hello from Tornado. ### Method GET ### Endpoint /hello ### Parameters #### Query Parameters - **name** (str) - Required - Name to greet ### Response #### Success Response (200) - **message** (str) - Greeting message ``` -------------------------------- ### Run with Hypercorn (Development) Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/quart.md Installs Hypercorn and runs the application with live reloading for development. ```bash pip install hypercorn hypercorn main:app --reload ``` -------------------------------- ### Install Dependencies with Poetry Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/community/contributing.md Use this command to install project dependencies if you are using Poetry. ```bash git clone https://github.com/yourusername/fastopenapi.git cd fastopenapi poetry install ``` -------------------------------- ### Install Dependencies Manually Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/community/contributing.md Install dependencies manually using pip if you are not using Poetry. ```bash pip install -e .[dev] ``` -------------------------------- ### Document Request Body Examples Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/advanced/openapi_customization.md Provide example values for request models using Field or json_schema_extra. ```python class UserCreate(BaseModel): username: str = Field(..., example="johndoe") email: EmailStr = Field(..., example="john@example.com") age: int = Field(..., example=25, ge=0, le=120) @router.post("/users") def create_user(user: UserCreate): return user ``` ```python class UserCreate(BaseModel): username: str email: EmailStr model_config = { "json_schema_extra": { "examples": [ { "username": "johndoe", "email": "john@example.com" }, { "username": "janedoe", "email": "jane@example.com" } ] } } ``` -------------------------------- ### Install Framework Extra for Imports Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/getting_started/quickstart.md If you encounter import errors, ensure you have installed the necessary framework extra using pip. ```bash pip install fastopenapi[your-framework] ``` -------------------------------- ### Setup Tornado with FastOpenAPI Source: https://context7.com/mr-fatalyst/fastopenapi/llms.txt Integrates FastOpenAPI with a Tornado application using the TornadoRouter. ```python import asyncio from pydantic import BaseModel from tornado.web import Application from fastopenapi.routers.tornado import TornadoRouter app = Application() router = TornadoRouter(app=app, title="Tornado API", version="1.0.0") class MessageResponse(BaseModel): message: str @router.get("/hello", tags=["Hello"], response_model=MessageResponse) def hello(name: str): """Say hello from Tornado""" return MessageResponse(message=f"Hello, {name}! It's Tornado!") async def main(): app.listen(8000) await asyncio.Event().wait() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### GET / Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/quart.md Returns a welcome message for the User Management API. ```APIDOC ## GET / ### Description Returns a welcome message for the User Management API. ### Method GET ### Endpoint / ### Response #### Success Response (200) - **message** (string) - Welcome message #### Response Example { "message": "User Management API" } ``` -------------------------------- ### Documenting Multiple Request Body Examples Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/advanced/openapi_customization.md Provide multiple examples for a request body to illustrate different valid input scenarios. ```APIDOC ### Multiple Examples ```python class UserCreate(BaseModel): username: str email: EmailStr model_config = { "json_schema_extra": { "examples": [ { "username": "johndoe", "email": "john@example.com" }, { "username": "janedoe", "email": "jane@example.com" } ] } } ``` ``` -------------------------------- ### Implement GET Endpoint Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/guide/routing.md Define a GET endpoint to retrieve resources. This example shows retrieving a list of items and a specific item by its ID. ```python @router.get("/items") def list_items(): return {"items": []} @router.get("/items/{item_id}") def get_item(item_id: int): return {"item_id": item_id} ``` -------------------------------- ### GET /products Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/examples/multi_router.md Retrieves a list of all available products. ```APIDOC ## GET /products ### Description List all products. ### Method GET ### Endpoint /products ### Response #### Success Response (200) - **products** (list[Product]) - A list of product objects. ``` -------------------------------- ### Execute Benchmark Suite Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/benchmarks/README.md Command to run the benchmark runner after starting the implementations. ```bash python benchmarks/common/benchmark.py ``` -------------------------------- ### Usage Example: Defining API Endpoints Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/advanced/custom_routers.md Example of using the custom router to define GET and POST endpoints for items. It utilizes Pydantic models for request and response validation. ```python from myframework import App from pydantic import BaseModel app = App() router = MyFrameworkRouter( app=app, title="My API", version="1.0.0" ) class Item(BaseModel): name: str price: float @router.get("/items/{item_id}") def get_item(item_id: int): return {"id": item_id, "name": "Test"} @router.post("/items", response_model=Item, status_code=201) def create_item(item: Item): return item ``` -------------------------------- ### Launch Application and Access Documentation Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/README.md Commands to start the server and access the generated Swagger or ReDoc interfaces. ```bash python main.py ``` ```text http://127.0.0.1:8000/docs ``` ```text http://127.0.0.1:8000/redoc ``` -------------------------------- ### Troubleshooting ImportError for Framework Router Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/getting_started/installation.md Example of an ImportError that occurs when a framework router is used without the corresponding framework extra installed. The solution is to install the required extra or the framework separately. ```python from fastopenapi.routers import FlaskRouter # ImportError: This framework is not installed. ``` -------------------------------- ### Basic AIOHTTP Router Setup Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/aiohttp.md Initialize the AioHttpRouter with an existing aiohttp application instance. ```python from aiohttp import web from pydantic import BaseModel from fastopenapi.routers import AioHttpRouter app = web.Application() router = AioHttpRouter( app=app, title="AIOHTTP API", version="1.0.0" ) class Item(BaseModel): name: str price: float @router.get("/") async def root(): return {"message": "Hello from AIOHTTP!"} @router.post("/items", response_model=Item, status_code=201) async def create_item(item: Item): return item if __name__ == "__main__": web.run_app(app, host="127.0.0.1", port=8000) ``` -------------------------------- ### Run FastAPI Application with Sample Data Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/examples/crud_api.md Initializes the application by creating sample users and then starts the development server. Access API documentation at http://localhost:5000/docs. ```python if __name__ == "__main__": for name, email in [("alice", "alice@example.com"), ("bob", "bob@example.com")]: create_user(UserCreate(username=name, email=email, full_name=name.title(), password="password123")) print("Sample users created! Docs at http://localhost:5000/docs") app.run(debug=True) ``` -------------------------------- ### Configure CORS with Quart-CORS Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/quart.md Install and configure `quart-cors` to handle Cross-Origin Resource Sharing. This example allows all origins. ```bash pip install quart-cors ``` ```python from quart_cors import cors app = Quart(__name__) app = cors(app, allow_origin="*") router = QuartRouter(app=app) ``` -------------------------------- ### Basic Quart Router Setup Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/quart.md Initialize a Quart application and configure the FastOpenAPI router. ```python from quart import Quart from pydantic import BaseModel from fastopenapi.routers import QuartRouter app = Quart(__name__) router = QuartRouter( app=app, title="Quart API", version="1.0.0" ) class Item(BaseModel): name: str price: float @router.get("/") async def root(): return {"message": "Hello from Quart!"} @router.post("/items", response_model=Item, status_code=201) async def create_item(item: Item): return item if __name__ == "__main__": app.run(port=8000) ``` -------------------------------- ### Include Router Usage Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/api_reference/routers.md Example of nesting a sub-router under a specific URL prefix. ```python from fastopenapi.routers import FlaskRouter # Main router main_router = FlaskRouter(app=app) # Sub-router for users users_router = FlaskRouter() @users_router.get("/{user_id}") def get_user(user_id: int): return {"user_id": user_id} @users_router.post("/") def create_user(username: str): return {"username": username} # Include users router with prefix main_router.include_router(users_router, prefix="/users") # Now available at: # GET /users/{user_id} # POST /users/ ``` -------------------------------- ### Flask-Caching Setup Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/advanced/performance.md Initializes Flask-Caching for response caching. Requires `Cache` from `flask_caching`. ```python from flask_caching import Cache ``` -------------------------------- ### Basic Flask Setup with FastOpenAPI Source: https://context7.com/mr-fatalyst/fastopenapi/llms.txt Set up a Flask application with automatic OpenAPI documentation using FlaskRouter. Access Swagger UI at /docs and ReDoc at /redoc. ```python from flask import Flask from pydantic import BaseModel from fastopenapi.routers import FlaskRouter app = Flask(__name__) router = FlaskRouter( app=app, title="My API", version="1.0.0", description="API documentation", docs_url="/docs", redoc_url="/redoc", openapi_url="/openapi.json" ) class HelloResponse(BaseModel): message: str @router.get("/hello", tags=["Hello"], status_code=200, response_model=HelloResponse) def hello(name: str): """Say hello from Flask""" return HelloResponse(message=f"Hello, {name}!") if __name__ == "__main__": app.run(port=8000) # Access docs at: http://127.0.0.1:8000/docs (Swagger UI) # Access docs at: http://127.0.0.1:8000/redoc (ReDoc) ``` -------------------------------- ### Configure CORS Support with django-cors-headers Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/django.md Enable Cross-Origin Resource Sharing (CORS) by installing and configuring `django-cors-headers`. This example shows how to add the app, middleware, and specify allowed origins. ```bash pip install django-cors-headers ``` -------------------------------- ### Database Integration with SQLAlchemy Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/quart.md Example of using SQLAlchemy with async sessions and dependency injection. ```python from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession from sqlalchemy.orm import sessionmaker from fastopenapi import Depends engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db") async_session = sessionmaker(engine, class_=AsyncSession) async def get_db(): async with async_session() as session: yield session @router.get("/users/{user_id}") async def get_user(user_id: int, db: AsyncSession = Depends(get_db)): result = await db.execute(select(User).where(User.id == user_id)) user = result.scalar_one_or_none() if not user: raise ResourceNotFoundError(f"User {user_id} not found") return {"id": user.id, "username": user.username} ``` -------------------------------- ### Configure Router Documentation Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/guide/routing.md Demonstrates how to set API metadata and documentation URLs during router initialization. ```python router = FlaskRouter( app=app, title="My API", # API title version="1.0.0", # API version description="My API documentation", # Description docs_url="/docs", # Swagger UI path redoc_url="/redoc", # ReDoc path openapi_url="/openapi.json", # OpenAPI schema path openapi_version="3.0.0", # OpenAPI spec version ) ``` ```python router = FlaskRouter( app=app, docs_url=None, # Disables all: Swagger UI, ReDoc, and OpenAPI JSON ) ``` ```python router = FlaskRouter( app=app, docs_url="/api-docs", # Custom Swagger UI path redoc_url="/api-documentation", # Custom ReDoc path openapi_url="/api-schema.json", # Custom schema path ) ``` -------------------------------- ### AioHTTP Async Framework Setup Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/advanced/performance.md AioHTTP offers good performance for async applications. Requires `fastopenapi.routers.AioHttpRouter`. ```python from aiohttp import web from fastopenapi.routers import AioHttpRouter app = web.Application() router = AioHttpRouter(app=app) @router.get("/items") async def list_items(): return await db.query_items() ``` -------------------------------- ### Complete API Integration Example Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/advanced/openapi_customization.md A full implementation demonstrating FlaskRouter initialization, Pydantic model definitions, and route decorators with OpenAPI metadata. ```python from flask import Flask from pydantic import BaseModel, EmailStr, Field from fastopenapi.routers import FlaskRouter from fastopenapi import Path, Query app = Flask(__name__) router = FlaskRouter( app=app, title="User Management API", version="2.0.0", description=""" # User Management System This API provides endpoints for managing users in the system. ## Features * Create, read, update, and delete users * Search and filter users * User authentication """, docs_url="/docs", redoc_url="/redoc", openapi_url="/openapi.json" ) class UserCreate(BaseModel): username: str = Field( ..., description="Unique username", example="johndoe", min_length=3, max_length=50 ) email: EmailStr = Field(..., example="john@example.com") full_name: str = Field(..., example="John Doe") class UserResponse(BaseModel): id: int = Field(..., description="User ID", example=1) username: str email: EmailStr full_name: str @router.get( "/users", response_model=list[UserResponse], tags=["Users"], summary="List all users", description="Retrieve a paginated list of all users", responses={ 200: {"description": "Successful response"}, 500: {"description": "Internal server error"} } ) def list_users( page: int = Query(1, description="Page number", ge=1), limit: int = Query(10, description="Items per page", ge=1, le=100) ): """List users with pagination.""" return [] @router.get( "/users/{user_id}", response_model=UserResponse, tags=["Users"], summary="Get user by ID", responses={ 200: {"description": "User found"}, 404: {"description": "User not found"} } ) def get_user( user_id: int = Path(..., description="User ID", example=1, ge=1) ): """Retrieve a single user by ID.""" return UserResponse( id=user_id, username="johndoe", email="john@example.com", full_name="John Doe" ) @router.post( "/users", response_model=UserResponse, status_code=201, tags=["Users"], summary="Create new user", responses={ 201: {"description": "User created successfully"}, 400: {"description": "Invalid input"} } ) def create_user(user: UserCreate): """Create a new user.""" return UserResponse(id=1, **user.model_dump()) if __name__ == "__main__": print("API Documentation: http://localhost:5000/docs") app.run(debug=True) ``` -------------------------------- ### Create Quart App with FastOpenAPI Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/getting_started/quickstart.md Set up a Quart application and integrate FastOpenAPI for routing and API definition. Requires `fastopenapi[quart]` installation. ```python from quart import Quart from pydantic import BaseModel from fastopenapi.routers import QuartRouter # Create Quart app app = Quart(__name__) # Create FastOpenAPI router router = QuartRouter( app=app, title="My Quart API", version="1.0.0" ) class Item(BaseModel): name: str price: float @router.get("/") async def root(): return {"message": "Hello from Quart!"} @router.get("/items/{item_id}") async def get_item(item_id: int): return {"item_id": item_id} @router.post("/items", response_model=Item, status_code=201) async def create_item(item: Item): return item if __name__ == "__main__": app.run(port=8000) ``` -------------------------------- ### Basic Authentication Setup Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/guide/security.md Implements Basic Auth by decoding the Authorization header and verifying credentials against a user database. ```python import base64 from fastopenapi import Header router = FlaskRouter( app=app, security_scheme=SecuritySchemeType.BASIC_AUTH ) def verify_basic_auth(authorization: str = Header(..., alias="Authorization")): if not authorization.startswith("Basic "): raise AuthenticationError("Invalid authorization header") # Decode base64 encoded = authorization[6:] try: decoded = base64.b64decode(encoded).decode("utf-8") username, password = decoded.split(":", 1) except Exception: raise AuthenticationError("Invalid authorization format") # Verify credentials user = authenticate_user(username, password) if not user: raise AuthenticationError("Invalid credentials") return user @router.get("/protected") def protected_endpoint(user = Depends(verify_basic_auth)): return {"message": f"Hello, {user.username}"} ``` -------------------------------- ### GET /users/{user_id}/posts/{post_id} Source: https://context7.com/mr-fatalyst/fastopenapi/llms.txt Get a specific post by user and post ID. ```APIDOC ## GET /users/{user_id}/posts/{post_id} ### Description Get a specific post by user and post ID. ### Method GET ### Endpoint /users/{user_id}/posts/{post_id} ### Parameters #### Path Parameters - **user_id** (int) - Required - User ID - **post_id** (int) - Required - Post ID ``` -------------------------------- ### Create Tornado App with FastOpenAPI Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/getting_started/quickstart.md Set up a Tornado application and integrate FastOpenAPI for routing and API definition. Requires `fastopenapi[tornado]` installation. ```python import asyncio from tornado.web import Application from pydantic import BaseModel from fastopenapi.routers import TornadoRouter # Create Tornado app app = Application() # Create FastOpenAPI router router = TornadoRouter( app=app, title="My Tornado API", version="1.0.0" ) class Item(BaseModel): name: str price: float @router.get("/") async def root(): return {"message": "Hello from Tornado!"} @router.get("/items/{item_id}") async def get_item(item_id: int): return {"item_id": item_id} @router.post("/items", response_model=Item, status_code=201) async def create_item(item: Item): return item async def main(): app.listen(8000) print("Server started on http://localhost:8000") print("Documentation at http://localhost:8000/docs") await asyncio.Event().wait() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Deploy the application Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/starlette.md Commands for running the application in development and production environments. ```bash uvicorn main:app --reload ``` ```bash uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4 ``` ```bash gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker --bind 0.0.0.0:8000 ``` -------------------------------- ### Verify FastOpenAPI Installation Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/getting_started/installation.md Checks if FastOpenAPI is installed correctly by importing the library and printing its version number. ```python import fastopenapi print(fastopenapi.__version__) ``` -------------------------------- ### Test API with httpie (GET) Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/getting_started/quickstart.md Perform a GET request to the /items/{item_id} endpoint using httpie. ```bash # GET request http :8000/items/1 ``` -------------------------------- ### Follow Best Practices for Naming and REST Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/guide/routing.md Provides examples of descriptive naming and standard RESTful collection operations. ```python # Good @router.get("/users/{user_id}") def get_user(user_id: int): pass # Bad @router.get("/users/{id}") def get(id: int): pass ``` ```python # Collection operations @router.get("/items") # List items @router.post("/items") # Create item ``` -------------------------------- ### Test API with curl (GET) Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/getting_started/quickstart.md Perform a GET request to the /items/{item_id} endpoint using curl. ```bash # GET request curl http://localhost:8000/items/1 ``` -------------------------------- ### Framework-Specific Router Implementations Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/api_reference/routers.md Examples of initializing FastOpenAPI routers for various Python web frameworks. ```python from flask import Flask from fastopenapi.routers import FlaskRouter app = Flask(__name__) router = FlaskRouter( app=app, title="Flask API", version="1.0.0" ) @router.get("/items") def list_items(): return {"items": []} if __name__ == "__main__": app.run() ``` ```python import uvicorn from starlette.applications import Starlette from fastopenapi.routers import StarletteRouter app = Starlette() router = StarletteRouter( app=app, title="Starlette API", version="1.0.0" ) @router.get("/items") async def list_items(): return {"items": []} if __name__ == "__main__": uvicorn.run(app) ``` ```python from aiohttp import web from fastopenapi.routers import AioHttpRouter app = web.Application() router = AioHttpRouter( app=app, title="AioHTTP API", version="1.0.0" ) @router.get("/items") async def list_items(): return {"items": []} if __name__ == "__main__": web.run_app(app) ``` ```python from sanic import Sanic from fastopenapi.routers import SanicRouter app = Sanic("MyApp") router = SanicRouter( app=app, title="Sanic API", version="1.0.0" ) @router.get("/items") async def list_items(): return {"items": []} if __name__ == "__main__": app.run() ``` ```python from quart import Quart from fastopenapi.routers import QuartRouter app = Quart(__name__) router = QuartRouter( app=app, title="Quart API", version="1.0.0" ) @router.get("/items") async def list_items(): return {"items": []} if __name__ == "__main__": app.run() ``` ```python from falcon import App from fastopenapi.routers import FalconRouter app = App() router = FalconRouter( app=app, title="Falcon API", version="1.0.0" ) @router.get("/items") def list_items(): return {"items": []} # For async Falcon: # from fastopenapi.routers import FalconAsyncRouter # router = FalconAsyncRouter(app=app) ``` ```python from django.urls import path from fastopenapi.routers import DjangoRouter router = DjangoRouter(app=True) @router.get("/items") def list_items(): return {"items": []} urlpatterns = [path("", router.urls)] # For async Django: # from fastopenapi.routers import DjangoAsyncRouter # router = DjangoAsyncRouter(app=True) ``` ```python import asyncio from tornado.web import Application from fastopenapi.routers import TornadoRouter app = Application() router = TornadoRouter( app=app, title="Tornado API", version="1.0.0" ) @router.get("/items") async def list_items(): return {"items": []} async def main(): app.listen(8000) await asyncio.Event().wait() if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Invalid Request Example Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/guide/error_handling.md An example of an invalid HTTP POST request payload that violates Pydantic model constraints. ```http POST /users Content-Type: application/json {"name": "John", "age": -5, "email": "invalid"} ``` -------------------------------- ### Implement a complete FastOpenAPI application Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/frameworks/starlette.md A full example demonstrating API routing, Pydantic models, and error handling with Starlette. ```python import uvicorn from starlette.applications import Starlette from pydantic import BaseModel, EmailStr from fastopenapi.routers import StarletteRouter from fastopenapi.errors import ResourceNotFoundError from fastopenapi import Query app = Starlette() router = StarletteRouter( app=app, title="User Management API", version="1.0.0" ) users_db = {} next_id = 1 class UserResponse(BaseModel): id: int username: str email: str class UserCreate(BaseModel): username: str email: EmailStr @router.get("/", tags=["Root"]) async def root(): return {"message": "User Management API"} @router.get("/users", response_model=list[UserResponse], tags=["Users"]) async def list_users(limit: int = Query(10, ge=1, le=100)): users = list(users_db.values())[:limit] return users @router.get("/users/{user_id}", response_model=UserResponse, tags=["Users"]) async def get_user(user_id: int): user = users_db.get(user_id) if not user: raise ResourceNotFoundError(f"User {user_id} not found") return user @router.post("/users", response_model=UserResponse, status_code=201, tags=["Users"]) async def create_user(user: UserCreate): global next_id new_user = { "id": next_id, "username": user.username, "email": user.email } users_db[next_id] = new_user next_id += 1 return new_user @router.delete("/users/{user_id}", status_code=204, tags=["Users"]) async def delete_user(user_id: int): if user_id not in users_db: raise ResourceNotFoundError(f"User {user_id} not found") del users_db[user_id] return None if __name__ == "__main__": uvicorn.run(app, host="127.0.0.1", port=8000) ``` -------------------------------- ### Create Falcon App with FastOpenAPI Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/getting_started/quickstart.md Set up a Falcon application and integrate FastOpenAPI for routing and API definition. Requires `fastopenapi[falcon]` installation. ```python from fastopenapi.routers import FalconAsyncRouter from pydantic import BaseModel import falcon.asgi import uvicorn # Create Falcon app app = falcon.asgi.App() # Create FastOpenAPI router router = FalconAsyncRouter( app=app, title="My Falcon API", version="1.0.0" ) class Item(BaseModel): name: str price: float @router.get("/") async def root(): return {"message": "Hello from Falcon!"} @router.get("/items/{item_id}") async def get_item(item_id: int): return {"item_id": item_id} @router.post("/items", response_model=Item, status_code=201) async def create_item(item: Item): return item if __name__ == "__main__": uvicorn.run(app, host="127.0.0.1", port=8000) ``` -------------------------------- ### Test API with Python requests (GET) Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/getting_started/quickstart.md Perform a GET request to the /items/{item_id} endpoint using the Python requests library. ```python import requests # GET request response = requests.get("http://localhost:8000/items/1") print(response.json()) ``` -------------------------------- ### Install Pre-commit Hooks Source: https://github.com/mr-fatalyst/fastopenapi/blob/master/docs/community/contributing.md Install pre-commit hooks to ensure clean code before committing. These hooks automate code formatting, linting, and import sorting. ```bash pre-commit install ```