Skip to content
TheChatArchiveThe Chat Archive
Coherecommand-a-03-2025· CohereHugging Face LMArena Human Preference 140K

Now tell me the basics of using FastAPI

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Amazon Novaamazon.nova-pro-v1:0’s answer.
  1. User

    Now tell me the basics of using FastAPI

  2. Cohere Assistant

    FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints. It is designed to provide the following key features:

    1. Fast: High performance, on par with Node.js and Go, thanks to Starlette and Pydantic.
    2. Intuitive: Great editor support with auto-completion and fewer errors due to its use of type hints.
    3. Easy to Use: Designed to be easy to use and learn, with a minimal learning curve.
    4. Robust: Automatic interactive API documentation with Swagger UI and ReDoc.
    5. Async: Supports asynchronous request handling with async/await syntax.

    Below is a comprehensive introduction to the basics of using FastAPI.


    1. Installation

    First, install FastAPI and an ASGI server (like Uvicorn) to run your application:

    pip install fastapi uvicorn
    

    2. Basic "Hello World" Example

    Create a file named main.py with the following content:

    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/")
    def read_root():
        return {"message": "Hello, World!"}
    
    # Run with: uvicorn main:app --reload
    

    Run the application using Uvicorn:

    uvicorn main:app --reload
    
    • main is the Python file.
    • app is the FastAPI instance.
    • --reload enables auto-reloading during development.

    Visit http://127.0.0.1:8000/ in your browser to see the JSON response.


    3. Path Parameters

    Define dynamic routes using path parameters:

    @app.get("/items/{item_id}")
    def read_item(item_id: int, q: str = None):
        return {"item_id": item_id, "q": q}
    
    • Access this endpoint at http://127.0.0.1:8000/items/42?q=test.
    • item_id is automatically converted to an integer due to the type hint.

    4. Query Parameters

    Handle query parameters with type hints and default values:

    from typing import Optional
    
    @app.get("/items/")
    def read_items(skip: int = 0, limit: int = 10, q: Optional[str] = None):
        return {"skip": skip, "limit": limit, "q": q}
    
    • Access this endpoint at http://127.0.0.1:8000/items/?skip=10&limit=5&q=search.

    5. Request Bodies

    Use Pydantic models to validate and handle request bodies:

    from pydantic import BaseModel
    
    class Item(BaseModel):
        name: str
        description: str = None
        price: float
        tax: float = None
    
    @app.post("/items/")
    def create_item(item: Item):
        return item
    

    Send a POST request to http://127.0.0.1:8000/items/ with a JSON body:

    {
        "name": "Foo",
        "description": "A very nice Item",
        "price": 35.4,
        "tax": 3.2
    }
    

    6. Automatic Documentation

    FastAPI automatically generates interactive API documentation:

    • Swagger UI: Access at http://127.0.0.1:8000/docs.
    • ReDoc: Access at http://127.0.0.1:8000/redoc.

    7. Error Handling

    FastAPI automatically handles errors and returns appropriate HTTP responses. You can also raise HTTP exceptions manually:

    from fastapi import HTTPException
    
    @app.get("/items/{item_id}")
    def read_item(item_id: int):
        if item_id == 404:
            raise HTTPException(status_code=404, detail="Item not found")
        return {"item_id": item_id}
    

    8. Dependencies

    Reuse common functionality across multiple paths using dependencies:

    from fastapi import Depends
    
    def query_extractor(q: str = None):
        return q
    
    @app.get("/items/")
    def read_items(q: str = Depends(query_extractor)):
        return {"q": q}
    

    Dependencies can be classes, functions, or even third-party libraries.


    9. Asynchronous Support

    FastAPI supports asynchronous code using async def:

    import asyncio
    
    @app.get("/async")
    async def async_example():
        await asyncio.sleep(1)
        return {"message": "Async task completed"}
    

    10. Security

    Add authentication and authorization using dependencies:

    from fastapi.security import OAuth2PasswordBearer
    
    oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
    
    @app.get("/protected")
    def protected_route(token: str = Depends(oauth2_scheme)):
        return {"token": token}
    

    11. Background Tasks

    Run tasks in the background after returning a response:

    from fastapi import BackgroundTasks
    
    def write_notification(email: str, message=""):
        with open("log.txt", mode="w") as email_file:
            content = f"notification for {email}: {message}"
            email_file.write(content)
    
    @app.post("/send-notification/{email}")
    def send_notification(email: str, background_tasks: BackgroundTasks):
        background_tasks.add_task(write_notification, email, message="some notification")
        return {"message": "Notification sent in the background"}
    

    12. Middleware

    Add middleware for request/response processing:

    from fastapi.middleware.cors import CORSMiddleware
    
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    

    13. Testing

    Test your FastAPI application using TestClient:

    from fastapi.testclient import TestClient
    
    client = TestClient(app)
    
    def test_read_main():
        response = client.get("/")
        assert response.status_code == 200
        assert response.json() == {"message": "Hello, World!"}
    

    14. Deployment

    Deploy your FastAPI application using:

    • Uvicorn for production (with Gunicorn for scaling):

      pip install gunicorn
      gunicorn -k uvicorn.workers.UvicornWorker main:app
      
    • Docker, Kubernetes, or cloud platforms like Heroku, Vercel, or AWS.


    Example: Full Application

    Here’s a complete example combining multiple features:

    from fastapi import FastAPI, HTTPException, Depends
    from pydantic import BaseModel
    from typing import Optional, List
    
    app = FastAPI()
    
    class Item(BaseModel):
        name: str
        description: Optional[str] = None
        price: float
        tax: Optional[float] = None
    
    class User(BaseModel):
        username: str
    
    # Fake database
    fake_db = {}
    
    def get_current_user(user: User = Depends()):
        return user
    
    @app.post("/items/")
    def create_item(item: Item, user: User = Depends(get_current_user)):
        if user.username not in fake_db:
            fake_db[user.username] = []
        fake_db[user.username].append(item)
        return item
    
    @app.get("/items/", response_model=List[Item])
    def read_items(user: User = Depends(get_current_user)):
        if user.username not in fake_db:
            raise HTTPException(status_code=404, detail="No items found")
        return fake_db[user.username]
    
    # Run with: uvicorn main:app --reload
    

    Key Takeaways

    • Use type hints for automatic data validation and documentation.
    • Leverage FastAPI's built-in features like automatic docs, error handling, and dependencies.
    • Write asynchronous code with async def for better performance.
    • Test your application using TestClient.
    • Deploy with Uvicorn or other ASGI servers.

    FastAPI is designed to be intuitive and powerful, making it an excellent choice for building modern APIs. For more advanced topics, refer to the official documentation.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.