Getting started

FastAPI is a modern, high-performance web framework for building APIs with Python, based on standard Python type hints. It's known for its speed and ease of use, making it a popular choice for developers looking to build scalable and robust APIs.

Getting Started with FastAPI

  1. Setup Your Environment Make sure you have Python 3.7 or newer installed.
  2. Create Your First FastAPI Application* Create a new Python file, main.py, and start by writing a simple FastAPI app:
    from fastapi import FastAPI
    
    app = FastAPI()
    
    @app.get("/")
    def read_root():
        return {"Hello": "World"}
    ```* This code creates a basic FastAPI app with a single route, `/`, which returns a JSON response.
    
  3. Run Your Application* You can run your FastAPI application using uvicorn, an ASGI server:
    uvicorn main:app --reload
    ```* Here, `main` is the name of the Python file (without the `.py` extension) and `app` is the FastAPI instance. The `--reload` flag is used for auto-reloading during development.
    
  4. Access the Interactive API Documentation* Open your browser and go to http://127.0.0.1:8000/docs to see the automatically generated Swagger UI for your API.
    • You can also access the alternative ReDoc documentation at http://127.0.0.1:8000/redoc.
  5. Expanding Your Application* You can define more routes with various HTTP methods like GET, POST, PUT, DELETE, etc.:
    @app.get("/items/{item_id}")
    def read_item(item_id: int, q: str = None):
        return {"item_id": item_id, "q": q}
    
    @app.post("/items/")
    def create_item(item: dict):
        return {"item_name": item['name'], "item_price": item['price']}
    
  6. Using Pydantic for Data Validation* FastAPI leverages Pydantic models for data validation and parsing:
    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": item}
    ```* Here, `Item` is a Pydantic model that enforces the structure and types of data.
    
  7. Handling Dependencies* FastAPI supports dependency injection. You can define dependencies that can be shared across different endpoints:
    from fastapi import Depends
    
    def common_parameters(q: str = None, skip: int = 0, limit: int = 10):
        return {"q": q, "skip": skip, "limit": limit}
    
    @app.get("/items/")
    def read_items(commons: dict = Depends(common_parameters)):
        return commons
    

Additional Resources

  • Official Documentation: The FastAPI documentation is comprehensive and provides detailed guides and examples.
  • Tutorials: There are many tutorials available online that cover various aspects of FastAPI, from basic usage to advanced features like background tasks and WebSockets.
  • Community: Join the FastAPI community to ask questions, share knowledge, and learn from others.

Example Project Structure

For a more organized and scalable project, you might want to structure your FastAPI application as follows:

project/
├── app/
│   ├── __init__.py
│   ├── main.py
│   ├── models.py
│   ├── routes.py
│   ├── schemas.py
│   └── dependencies.py
├── tests/
│   ├── __init__.py
│   └── test_main.py
└── requirements.txt

This structure helps in maintaining clean and modular code, especially as your project grows.

With these basics, you should be well-equipped to start building applications with FastAPI.