Skip to main content

Overview

FastrAPI is designed as a drop-in replacement for FastAPI, which means migration is straightforward for most applications. In many cases, you only need to change your import statement.
FastrAPI maintains API compatibility with FastAPI’s core features, including decorators, Pydantic models, dependency injection, and middleware.

Basic migration

The simplest migration involves just updating your import statement.
1

Update imports

Change your FastAPI imports to FastrAPI:
- from fastapi import FastAPI
+ from fastrapi import FastrAPI

- app = FastAPI()
+ app = FastrAPI()
2

Update the server

Replace your ASGI server (Uvicorn/Gunicorn) with FastrAPI’s built-in server:
- # Old: Run with uvicorn
- # uvicorn main:app --host 0.0.0.0 --port 8000

+ # New: Built-in server
+ if __name__ == "__main__":
+     app.serve("0.0.0.0", 8000)
Then simply run:
python main.py
3

Test your application

Run your application and test all endpoints to ensure everything works as expected.

Side-by-side comparison

Before (FastAPI)

main.py
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class User(BaseModel):
    name: str
    age: int

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

@app.post("/users")
def create_user(user: User):
    return {"user": user.dict(), "created": True}

# Run with: uvicorn main:app --host 0.0.0.0 --port 8000

After (FastrAPI)

main.py
from fastrapi import FastrAPI
from pydantic import BaseModel

app = FastrAPI()

class User(BaseModel):
    name: str
    age: int

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

@app.post("/users")
def create_user(user: User):
    return {"user": user.dict(), "created": True}

if __name__ == "__main__":
    app.serve("0.0.0.0", 8000)

# Run with: python main.py

Feature compatibility

The following FastAPI features are fully supported in FastrAPI:
  • HTTP methods: GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
  • Pydantic models: Request and response validation
  • Path parameters: /users/{user_id}
  • Query parameters: /items?skip=0&limit=10
  • Request bodies: JSON, form data, multipart
  • Response models: Type hints and Pydantic models
  • Dependency injection: Function dependencies
  • Middleware: CORS, GZip, TrustedHost, Session
  • WebSockets: Full async WebSocket support
  • OpenAPI: Automatic schema generation
  • Type hints: Full Python type annotation support

Common migration scenarios

Middleware migration

Middleware syntax is nearly identical between FastAPI and FastrAPI.
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"]
)

Response types migration

from fastapi import FastAPI
from fastapi.responses import HTMLResponse, JSONResponse

app = FastAPI()

@app.get("/html", response_class=HTMLResponse)
def get_html():
    return "<h1>Hello</h1>"

WebSocket migration

from fastapi import FastAPI, WebSocket

app = FastAPI()

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_json({"echo": data})

Handling unsupported features

If your application uses features not yet supported by FastrAPI:
Status: Not yet implementedWorkaround: Consolidate routes into a single app for now. You can organize routes in separate files and import them:
routes/users.py
def register_user_routes(app):
    @app.get("/users")
    def list_users():
        return {"users": []}
    
    @app.post("/users")
    def create_user(user: User):
        return {"user": user}
main.py
from fastrapi import FastrAPI
from routes.users import register_user_routes

app = FastrAPI()
register_user_routes(app)

if __name__ == "__main__":
    app.serve("0.0.0.0", 8000)
Status: In developmentWorkaround: Initialize resources before calling app.serve():
from fastrapi import FastrAPI
import asyncio

app = FastrAPI()

# Startup logic
async def startup():
    print("Starting up...")
    # Initialize database, connections, etc.

# Shutdown logic
async def shutdown():
    print("Shutting down...")
    # Close connections, cleanup, etc.

if __name__ == "__main__":
    asyncio.run(startup())
    try:
        app.serve("0.0.0.0", 8000)
    finally:
        asyncio.run(shutdown())
Status: Not yet implementedWorkaround: Use a reverse proxy (nginx) to serve static files, or keep a small FastAPI instance just for static files alongside your FastrAPI application.
Status: Not yet implementedWorkaround: Handle exceptions within your route handlers:
@app.get("/items/{item_id}")
def get_item(item_id: int):
    try:
        item = get_item_from_db(item_id)
        return item
    except ItemNotFound:
        return {"error": "Item not found"}
    except Exception as e:
        return {"error": str(e)}

Performance comparison

After migration, you should see significant performance improvements:
MetricFastAPI + GunicornFastrAPIImprovement
Avg Latency21.08 ms0.59 ms35.7x faster
Requests/sec93731,36033.5x more
P95 Latency38.47 ms2.39 ms16.1x faster
P99 Latency93.42 ms11.12 ms8.4x faster
Actual performance gains depend on your application’s workload, hardware, and specific use case. Run your own benchmarks to measure improvements.

Migration checklist

Use this checklist to ensure a smooth migration:
  • Update imports from fastapi to fastrapi
  • Change FastAPI() to FastrAPI()
  • Replace ASGI server (Uvicorn) with app.serve()
  • Update middleware imports (e.g., fastrapi.middleware)
  • Update response type imports (e.g., fastrapi.responses)
  • Test all endpoints for correctness
  • Verify Pydantic model validation
  • Test WebSocket connections (if used)
  • Check middleware functionality
  • Update deployment scripts
  • Run performance benchmarks
  • Update documentation
  • Plan workarounds for unsupported features

Deployment changes

Before (FastAPI with Uvicorn)

# Dockerfile
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]

After (FastrAPI)

# Dockerfile
CMD ["python", "main.py"]
main.py
if __name__ == "__main__":
    app.serve("0.0.0.0", 8000)
FastrAPI’s built-in server is powered by Rust’s Tokio runtime and handles concurrency efficiently without needing multiple workers.

Gradual migration strategy

For large applications, consider a gradual migration:
1

Identify boundaries

Split your application into logical modules or services.
2

Migrate one module

Start with a non-critical module or service.
3

Run in parallel

Run FastAPI and FastrAPI services side by side using different ports.
4

Use a reverse proxy

Route traffic between services using nginx or a load balancer.
5

Monitor and compare

Monitor performance and correctness before migrating more modules.
6

Complete migration

Once confident, migrate remaining modules.

Getting help

If you encounter issues during migration:
  • Check the GitHub issues for known problems
  • Review the examples directory for working code
  • Open a new issue with details about your migration challenge
  • Join the community discussions

Next steps

Quickstart

Learn FastrAPI features in depth

Advanced features

Explore advanced FastrAPI capabilities

Performance tuning

Optimize your FastrAPI application

GitHub

Contribute to FastrAPI

Build docs developers (and LLMs) love