Step-by-Step Guide to Designing and Deploying a RESTful API with FastAPI

Prerequisites Before diving into the creation of your RESTful API with FastAPI, ensure you have the following prerequisites installed: Python: Version 3.6 or higher is required. Pip: Package installer for Python. Virtual Environment: (Optional but

Written by: Leo Nguyen

Published on: October 21, 2025

Prerequisites

Before diving into the creation of your RESTful API with FastAPI, ensure you have the following prerequisites installed:

  • Python: Version 3.6 or higher is required.
  • Pip: Package installer for Python.
  • Virtual Environment: (Optional but recommended) for dependency management.

Ensure you have a development environment set up, preferably using an IDE like Visual Studio Code or PyCharm for better code management.

Setting Up Your Development Environment

  1. Create a Virtual Environment:
    Begin by creating a virtual environment to handle your project dependencies separately.

    python -m venv fastapi_env
  2. Activate the Environment:
    Depending on your OS, activate the virtual environment.

    • On Windows:
      fastapi_envScriptsactivate
    • On macOS/Linux:
      source fastapi_env/bin/activate
  3. Install FastAPI and Uvicorn:
    FastAPI utilizes Uvicorn as an ASGI server. Install both with pip.

    pip install fastapi uvicorn

Project Structure

Establish a clean project structure for better manageability:

fastapi_project/
    ├── app/
    │   ├── __init__.py
    │   ├── main.py
    │   ├── models.py
    │   ├── schemas.py
    │   ├── routes.py
    │   └── database.py
    └── requirements.txt

Create these files as placeholders for further development.

Designing Models and Schemas

1. Define Database Models

Using SQLAlchemy as our ORM, define your data models in models.py. For example, if you’re creating a simple blog API, your model may look like this:

# app/models.py
from sqlalchemy import Column, Integer, String
from database import Base

class Post(Base):
    __tablename__ = "posts"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, index=True)
    content = Column(String)

2. Create Pydantic Schemas

Schemas are essential for validating request data. In schemas.py, create your Pydantic models.

# app/schemas.py
from pydantic import BaseModel

class PostBase(BaseModel):
    title: str
    content: str

class PostCreate(PostBase):
    pass

class Post(PostBase):
    id: int

    class Config:
        orm_mode = True

Database Configuration

1. Set Up Database Connection

Using SQLAlchemy, define your database connection in database.py.

# app/database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

2. Initialize the Database

Include a function to initialize the database and create tables.

# app/database.py
def init_db():
    Base.metadata.create_all(bind=engine)

Creating API Routes

1. Define CRUD Operations

Implement the CRUD operations in routes.py.

# app/routes.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from . import models, schemas
from .database import SessionLocal, init_db

router = APIRouter()

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@router.post("/posts/", response_model=schemas.Post)
def create_post(post: schemas.PostCreate, db: Session = Depends(get_db)):
    db_post = models.Post(**post.dict())
    db.add(db_post)
    db.commit()
    db.refresh(db_post)
    return db_post

@router.get("/posts/{post_id}", response_model=schemas.Post)
def read_post(post_id: int, db: Session = Depends(get_db)):
    db_post = db.query(models.Post).filter(models.Post.id == post_id).first()
    if db_post is None:
        raise HTTPException(status_code=404, detail="Post not found")
    return db_post

2. Include Router in Main Application

Integrate your routes in main.py.

# app/main.py
from fastapi import FastAPI
from . import models
from .database import init_db
from .routes import router

app = FastAPI()

# Initialize database
init_db()

# Include routers
app.include_router(router)

Running the API

To run your FastAPI application, execute the following command in the root directory of your project:

uvicorn app.main:app --reload

This command starts a server at http://127.0.0.1:8000, enabling you to test your RESTful API.

Testing Your API

Using Swagger UI

FastAPI automatically generates documentation. Navigate to http://127.0.0.1:8000/docs to access the interactive Swagger UI and test your API endpoints directly from your browser.

Sending Requests with CURL

You can also test your API using CURL. For example, to create a new post, use:

curl -X POST "http://127.0.0.1:8000/posts/" -H "Content-Type: application/json" -d '{"title": "My First Post", "content": "Hello World!"}'

Deployment Options

Deploying with Docker

  1. Create a Dockerfile:

    In your project root, create a Dockerfile for containerization.

    # Dockerfile
    FROM python:3.9
    
    WORKDIR /app
    COPY . .
    
    RUN pip install -r requirements.txt
    
    CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "80"]
  2. Build the Docker Image:

    Execute the following command to build your Docker image.

    docker build -t fastapi-app .
  3. Run the Docker Container:

    Run your container with this command:

    docker run -d -p 80:80 fastapi-app

Deploying on Cloud Platforms

Alternatively, consider deploying your FastAPI application on platforms like Heroku, AWS, or Google Cloud. Follow their specific documentation for deploying Python applications.

Conclusion

This guide has provided a structured pathway to design and deploy a RESTful API using FastAPI, covering everything from model design to deployment. FastAPI’s asynchronous capabilities allow for efficient API development, ensuring your projects remain scalable and maintainable. Happy coding!

Leave a Comment

Previous

FastAPI: The Ultimate Starter Tutorial for Building RESTful APIs

Next

Building a personal website/blog to showcase Python projects