FastAPI

Python Framework

FastAPI Documentation

Overview

FastAPI is a modern, fast web framework for building APIs with Python. Alkimist provides full support for FastAPI applications with automatic dependency management and ASGI server configuration.

Project Structure

A typical FastAPI application structure:

text
app/
  main.py
  routers/
requirements.txt

Health Check Endpoint

FastAPI applications must implement a /up endpoint. Here's how:

Basic Health Check

python
# app/main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/up")
async def health_check():
    return {"status": "ok"}

@app.get("/")
async def root():
    return {"message": "Hello World"}

Advanced Health Check with Dependencies

python
# app/main.py
from fastapi import FastAPI, status
from fastapi.responses import JSONResponse

app = FastAPI()

@app.get("/up")
async def health_check():
    # Check database connection
    try:
        # Add your database health check here
        # await database.execute("SELECT 1")
        return JSONResponse(
            content={"status": "ok"},
            status_code=status.HTTP_200_OK
        )
    except Exception as e:
        return JSONResponse(
            content={"status": "error", "message": str(e)},
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE
        )

Simple Text Response

python
# app/main.py
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse

app = FastAPI()

@app.get("/up", response_class=PlainTextResponse)
async def health_check():
    return "ok"

Requirements

Your requirements.txt should include:

text
fastapi>=0.104.0
uvicorn[standard]>=0.24.0

ASGI Server

Alkimist automatically configures Uvicorn as the ASGI server. The application will run with:

bash
uvicorn app.main:app --host 0.0.0.0 --port 8000

Environment Variables

Common FastAPI environment variables:

  • DATABASE_URL (for database connections)
  • REDIS_URL (if using Redis)
  • ENVIRONMENT=production

Example Project

A minimal FastAPI application:

python
# app/main.py
from fastapi import FastAPI

app = FastAPI(title="My API")

@app.get("/up")
async def health_check():
    return "ok"

@app.get("/")
async def root():
    return {"message": "Hello from FastAPI"}

The health check will be available at /up and return "ok" when healthy.