Getting Started with FastAPI: A Modern Web Framework for APIs

Getting Started with FastAPI: A Modern Web Framework for APIs
Photo by SpaceX / Unsplash

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python. It is designed to be easy to use while providing the power of asynchronous programming and automatic validation. Built with Python type hints, FastAPI enables developers to create robust APIs quickly and efficiently.

Why Choose FastAPI?

  1. High Performance: As the name suggests, FastAPI is one of the fastest web frameworks available, thanks to its asynchronous capabilities and reliance on Starlette and Pydantic.
  2. Automatic Validation: FastAPI automatically validates request data using Python type hints, reducing boilerplate code.
  3. Interactive Documentation: It generates OpenAPI and Swagger UI documentation automatically.
  4. Easy to Learn: Its simple syntax makes it accessible to both beginners and experienced developers.
  5. Asynchronous Support: Built-in support for asynchronous programming using async and await.

Setting Up FastAPI

To get started with FastAPI, ensure you have Python installed, then follow these steps:

  1. Access the Automatic Documentation:
    • OpenAPI documentation: http://127.0.0.1:8000/docs
    • ReDoc documentation: http://127.0.0.1:8000/redoc

Run the Application:

uvicorn main:app --reload

Visit http://127.0.0.1:8000/ in your browser to see the response {"message": "Hello, FastAPI!"}.

Create a Simple FastAPI App: Create a new file main.py and add the following code:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello, FastAPI!"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)

Install FastAPI and Uvicorn (ASGI Server):

pip install fastapi uvicorn

Creating API Endpoints

FastAPI makes it easy to define API endpoints with different HTTP methods:

@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "query": q}

Here, item_id is an integer, and q is an optional query parameter.

Using Pydantic for Data Validation

FastAPI uses Pydantic for request body validation. Define a model in models.py:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = False

Use this model in an API endpoint:

@app.post("/items/")
async def create_item(item: Item):
    return {"name": item.name, "price": item.price, "is_offer": item.is_offer}

Now, when sending a POST request to /items/, FastAPI will automatically validate the data.

Adding Authentication

FastAPI supports OAuth2 and JWT authentication out of the box:

from fastapi.security import OAuth2PasswordBearer
from fastapi import Depends

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
    return {"token": token}

Connecting FastAPI to a Database

FastAPI supports various databases through SQLAlchemy. To install SQLAlchemy:

pip install sqlalchemy databases

Example model:

from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(bind=engine)
Base = declarative_base()

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String, unique=True, index=True)

Conclusion

FastAPI is an excellent choice for building high-performance, modern APIs with Python. Its built-in validation, asynchronous support, and auto-generated documentation make development faster and more efficient. Whether you're working on a simple microservice or a large-scale application, FastAPI is a powerful tool worth exploring. Happy coding!