FastAPI is a modern, fast (high-performance), web framework for building APIs in Python. It leverages Python’s type hints for automatic validation and documentation, making it highly developer-friendly. Below is a step-by-step guide to creating a FastAPI controllers and models, detailed for clarity.
Table of Contents
FAST API controllers and models creation step by step in 2025
FastAPI is a modern and fast web framework for building APIs using Python. It stands out for its speed, both in terms of performance and developer productivity. Built with Python’s type annotations in mind, FastAPI provides automatic data validation, serialization, and API documentation, which saves time and reduces errors.
Here are some of the most notable features of FastAPI:
1. Automatic API Documentation
FastAPI automatically generates interactive documentation for your APIs using Swagger UI and ReDoc. This is especially helpful for testing and exploring endpoints without additional effort.
2. High Performance
FastAPI is built on top of Starlette and Pydantic. Thanks to its asynchronous capabilities and dependency injection system, it’s one of the fastest Python frameworks available, comparable to Node.js or Go.
3. Pythonic and Easy to Use
FastAPI uses Python’s native type hints, making the code intuitive, clean, and easy to debug. The framework also handles request validation, response serialization, and error handling with minimal boilerplate code.
4. Built-in Validation
Using Pydantic, FastAPI validates incoming request data automatically. It ensures that your API endpoints receive properly formatted data and provides detailed error messages when validation fails.
5. Dependency Injection
FastAPI has a built-in dependency injection system, allowing you to manage dependencies (like database connections or authentication logic) cleanly and efficiently. This makes your code reusable and modular.
6. Asynchronous Support
FastAPI is fully asynchronous, which means it can handle thousands of simultaneous connections without blocking. This is particularly useful for applications like real-time chat or APIs that deal with a high volume of requests.
7. Developer Productivity
FastAPI helps developers work faster by reducing repetitive tasks. Its design ensures fewer bugs by catching errors early, and the autogenerated documentation streamlines the development process.
8. Wide Ecosystem
FastAPI integrates seamlessly with popular Python libraries like SQLAlchemy, Alembic, and libraries for authentication like OAuth2. This makes it suitable for a variety of use cases, from simple CRUD apps to complex microservices.
9. Suitable for Modern APIs
FastAPI is designed with modern API standards like REST and OpenAPI in mind. It also supports WebSockets, GraphQL, and background tasks, making it versatile for different project needs.
10. Scalability
Whether you’re building a small-scale application or a large enterprise solution, FastAPI is scalable. It works well with containerized environments like Docker and orchestration tools like Kubernetes.
Use Cases for FastAPI
- REST APIs: Build feature-rich, secure, and well-documented APIs.
- Machine Learning Models: Serve ML models as APIs using libraries like TensorFlow or Scikit-learn.
- Real-time Applications: Handle WebSockets or async tasks efficiently.
- Microservices: Develop small, focused services that integrate with larger systems.
In summary, FastAPI is an excellent choice for developers looking for a powerful yet easy-to-use framework for API development. Its modern features, combined with its strong focus on performance and productivity, make it a go-to tool for many Python developers.
10 Popular MVC Frameworks in Python
How to create FAST API controller and model in 2025
1. Prerequisites
Ensure you have the following installed on your system:
- Python (version 3.7 or above)
- pip (Python package manager)
- FastAPI and Uvicorn installed. You can install them via pip:
pip install fastapi uvicorn
2. Project Setup
- Create a new directory for your FastAPI project:
mkdir fastapi_project cd fastapi_project
- Set up a virtual environment (optional but recommended):
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
3. Install Required Libraries
FastAPI relies on Pydantic for data validation and SQLAlchemy (or similar) for database interactions. Install them as follows:
pip install fastapi[all] sqlalchemy pydantic
4. Define a Data Model
Data models in FastAPI are created using Pydantic for input validation and SQLAlchemy for database schemas. Below, we’ll create a User
model.
Step 1: Create a models.py
File
- Create a file named
models.py
to define the database schema. - Import SQLAlchemy components and define the model.
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True, index=True)
name = Column(String, index=True)
email = Column(String, unique=True, index=True)
hashed_password = Column(String)
# Create the database engine
DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(DATABASE_URL)
# Create all tables in the database
Base.metadata.create_all(bind=engine)
Step 2: Create a schemas.py
File
Use Pydantic to define the data validation schemas:
- Create a
schemas.py
file. - Define the Pydantic models.
from pydantic import BaseModel, EmailStr
class UserBase(BaseModel):
name: str
email: EmailStr
class UserCreate(UserBase):
password: str
class UserRead(UserBase):
id: int
class Config:
orm_mode = True # Enable ORM integration
5. Set Up a Database Session
FastAPI integrates well with SQLAlchemy for managing database sessions.
- Create a
database.py
File Define the database connection and session management.
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
- Create a Dependency for Database Access Add a function to handle session lifecycle.
from sqlalchemy.orm import Session
from fastapi import Depends
from .database import SessionLocal
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
6. Create a Repository Layer
To handle database operations, create a repository module.
- Create a
crud.py
File Define functions for CRUD operations.
from sqlalchemy.orm import Session
from . import models, schemas
def get_user(db: Session, user_id: int):
return db.query(models.User).filter(models.User.id == user_id).first()
def get_user_by_email(db: Session, email: str):
return db.query(models.User).filter(models.User.email == email).first()
def create_user(db: Session, user: schemas.UserCreate):
hashed_password = user.password + "notreallyhashed" # Placeholder for hashing
db_user = models.User(name=user.name, email=user.email, hashed_password=hashed_password)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
7. Create a Controller
Controllers in FastAPI are just route handlers. Use the APIRouter
for modular organization.
- Create a
main.py
File Define the FastAPI app and route handlers.
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from . import models, schemas, crud
from .database import engine, get_db
# Initialize the database and app
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
@app.post("/users/", response_model=schemas.UserRead)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
db_user = crud.get_user_by_email(db, email=user.email)
if db_user:
raise HTTPException(status_code=400, detail="Email already registered")
return crud.create_user(db=db, user=user)
@app.get("/users/{user_id}", response_model=schemas.UserRead)
def read_user(user_id: int, db: Session = Depends(get_db)):
db_user = crud.get_user(db, user_id=user_id)
if db_user is None:
raise HTTPException(status_code=404, detail="User not found")
return db_user
8. Test the API -FAST API controllers and models
- Run the Server Use Uvicorn to start the server:
uvicorn main:app --reload
- Access the API Documentation Visit the auto-generated Swagger UI at:
http://127.0.0.1:8000/docs
9. Advanced Features in FAST API controllers and models
After the basic setup, you can expand your FastAPI project with features like:
- JWT Authentication Use the
fastapi-jwt-auth
library for secure authentication. - Custom Middleware Add middleware for logging, authentication, or request transformations.
- Background Tasks Use FastAPI’s background task feature for deferred processing.
- Asynchronous Database Queries Integrate with async libraries like
Databases
for non-blocking queries.
10. Directory Structure FAST API controllers and models
Here’s how the final directory structure looks:
fastapi_project/
├── main.py # FastAPI app and controllers
├── models.py # SQLAlchemy models
├── schemas.py # Pydantic schemas
├── crud.py # Repository for database operations
├── database.py # Database connection and session handling
├── test.db # SQLite database file (auto-created)
Notes FAST API controllers and models
FAST API controllers and models: This step-by-step guide provides a foundational understanding of creating a FastAPI controller and model. From defining models to implementing routes and handling database operations, the modularity and speed of FastAPI make it a powerful framework for modern API development. You can further enhance this setup with advanced features, better database practices, and deployment strategies.