Fast API

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It's designed for ease of use and efficiency, making it ideal for quickly developing robust APIs. This tutorial will guide you through creating a basic FastAPI application.

Step-by-Step FastAPI Tutorial

1. Set Up Your Development Environment

  1. Install Python: Ensure you have Python 3.7 or later installed.
  2. Create a Project Directory:
    mkdir fastapi_tutorial
    cd fastapi_tutorial
    
  3. Set Up a Virtual Environment:
    python -m venv venv
    source venv/bin/activate  # On Windows, use `venv\Scripts\activate`
    
  4. Install FastAPI and Uvicorn:
    pip install fastapi uvicorn
    
    • FastAPI: The web framework.
    • Uvicorn: An ASGI server to serve your FastAPI application.

2. Create a Basic FastAPI Application

  1. Create main.py:
    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/")
    def read_root():
        return {"Hello": "World"}
    
  2. Run the Application:
    uvicorn main:app --reload
    
    • main: The file main.py (without the .py).
    • app: The FastAPI instance.
    • --reload: Enable auto-reload on code changes.
  3. Test the Application: Open a browser and go to http://127.0.0.1:8000/ to see {"Hello": "World"}.

3. Defining Routes and Handling HTTP Methods

  1. Add More Routes in main.py:
    @app.get("/items/{item_id}")
    def read_item(item_id: int, q: str = None):
        return {"item_id": item_id, "q": q}
    
    • This route captures item_id as a path parameter and q as an optional query parameter.
  2. Test the Route: Visit http://127.0.0.1:8000/items/1?q=testing.

4. Using Pydantic Models for Data Validation

  1. Define a Data Model: Create a file named models.py:
    from pydantic import BaseModel
    
    class Item(BaseModel):
        name: str
        description: str = None
        price: float
        tax: float = None
    
  2. Update main.py to Use the Model:
    from fastapi import FastAPI
    from models import Item
    
    app = FastAPI()
    
    @app.post("/items/")
    def create_item(item: Item):
        return {"item": item}
    
  3. Test the POST Endpoint: Use a tool like Postman or curl:
    curl -X 'POST' \
      'http://127.0.0.1:8000/items/' \
      -H 'Content-Type: application/json' \
      -d '{"name": "Apple", "price": 1.2, "description": "A juicy fruit", "tax": 0.1}'
    

    The response should echo the JSON back, validating the structure based on the Item model.

5. Dependency Injection

  1. Create a Dependency:
    from fastapi import Depends
    
    def common_parameters(q: str = None, skip: int = 0, limit: int = 10):
        return {"q": q, "skip": skip, "limit": limit}
    
  2. Use the Dependency in Routes:
    @app.get("/items/")
    def read_items(commons: dict = Depends(common_parameters)):
        return commons
    
  3. Test the Dependency: Visit http://127.0.0.1:8000/items/?q=fastapi&skip=10&limit=5.

6. Serving HTML and Static Files

  1. Install Jinja2 for Templating:
    pip install jinja2
    
  2. Create a Templates Directory: Create a folder named templates and add item.html:
    <!DOCTYPE html>
    <html>
    <head>
        <title>{{ title }}</title>
    </head>
    <body>
        <h1>{{ title }}</h1>
        <p>{{ description }}</p>
    </body>
    </html>
    
  3. Add a Static Directory: Create a folder named static and add your static files (e.g., CSS, JS).
  4. Serve HTML from FastAPI:
    from fastapi import FastAPI, Request
    from fastapi.responses import HTMLResponse
    from fastapi.templating import Jinja2Templates
    
    app = FastAPI()
    
    templates = Jinja2Templates(directory="templates")
    
    @app.get("/items/{id}", response_class=HTMLResponse)
    def read_item(request: Request, id: str):
        return templates.TemplateResponse("item.html", {"request": request, "title": "Item", "description": f"Item {id}"})
    
  5. Test the HTML Endpoint: Visit http://127.0.0.1:8000/items/123.

7. Advanced Features

  1. Background Tasks:
    from fastapi import BackgroundTasks
    
    def write_log(message: str):
        with open("log.txt", "a") as log:
            log.write(message + "\n")
    
    @app.post("/log/")
    def log_message(message: str, background_tasks: BackgroundTasks):
        background_tasks.add_task(write_log, message)
        return {"message": "Message received"}
    
  2. WebSockets:
    from fastapi import WebSocket
    
    @app.websocket("/ws")
    async def websocket_endpoint(websocket: WebSocket):
        await websocket.accept()
        while True:
            data = await websocket.receive_text()
            await websocket.send_text(f"Message text was: {data}")
    
  3. OAuth2 with Password (and Bearer) Tokens:
    from fastapi.security import OAuth2PasswordBearer
    
    oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
    
    @app.get("/users/me")
    async def read_users_me(token: str = Depends(oauth2_scheme)):
        return {"token": token}
    

8. Deployment

  1. Prepare for Deployment:
    • Remove --reload and set debug=False.
    • Use an ASGI server like Uvicorn or Hypercorn for production.
  2. Deploy with Uvicorn:
    uvicorn main:app --host 0.0.0.0 --port 80
    
  3. Use Docker:
    • Create a Dockerfile:
      FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7
      COPY ./app /app
      
    • Build and run the Docker image:
      docker build -t fastapi-app .
      docker run -d --name fastapi-container -p 80:80 fastapi-app
      
  4. Deploy on Cloud Platforms:
    • Use platforms like AWS, Google Cloud, Heroku, or DigitalOcean with specific FastAPI deployment guides.

Summary

FastAPI simplifies the development of fast and robust APIs by leveraging Python's type hints. This tutorial covers the basics to get you started, from setting up the environment to deploying your application. With FastAPI's powerful features and the ability to handle complex use cases, you can build highly scalable applications.

For further reading and tutorials:

Feel free to ask if you need more details on any specific part of FastAPI!