How to build REST API with FastAPI in Python

build REST API with FastAPI

As a Python developer, you’ve probably built small scripts, data tools, or Flask/Django applications. But when it comes to building modern APIs that are fast, type-safe, and developer-friendly, nothing matches FastAPI.

In this article, you’ll learn FastAPI by doing — through a real-world case study where we’ll design, build, and test APIs for a Sports Academy Management System managed by four friends: Sachin, Sourav, Dravid, and Sania.

Let’s dive into their story and build a real project together!

Why FastAPI?

FastAPI is a modern, async web framework built on Starlette and Pydantic.

âś… Key Advantages:

  • Ultra-fast performance — powered by ASGI and async I/O
  • Automatic docs via Swagger UI (/docs) and ReDoc (/redoc)
  • Type safety with Pydantic
  • Async-ready for modern microservices
  • Production-ready — used by companies like Uber, Microsoft, and Netflix

The Story: “The Sports Academy”

Our case study revolves around four friends who open a sports academy in Bangalore:

PersonRoleResponsibility
SachinCricket CoachTeaches cricket
SouravAdminManages student registrations
DravidOperations HeadManages training schedules
SaniaFinance & Customer CareHandles payments and feedback

Their academy has students like Ramesh, Priya, Arjun, and Meena who join different sports.

They decide to build a backend API (using FastAPI) to manage:

  • Student registrations
  • Schedules
  • Payments
  • Feedback

Let’s see how they do it step by step.

Step 1: Setting up FastAPI

Install the required packages:

Python
pip install fastapi uvicorn
Python

Create a file called main.py in your project folder:

main.py
from fastapi import FastAPI

app = FastAPI(title="Sports Academy API")

@app.get("/")
def home():
    return {"message": "Welcome to Sachin & Team Sports Academy"}
Python

Run the app:

ShellScript
python -m uvicorn main:app --reload
ShellScript

Visit 👉 http://127.0.0.1:8000/docs — you’ll see your auto-generated Swagger UI.
That’s your first API running in seconds!

Step 2: Student Registration (by Sourav)

Python
from pydantic import BaseModel

class Student(BaseModel):
    id: int
    name: str
    age: int
    sport: str

students_db = []

@app.post("/students/")
def register_student(student: Student):
    students_db.append(student.dict())
    return {"message": f"{student.name} registered for {student.sport}"}

@app.get("/students/")
def list_students():
    return students_db
Python

âś… Example:

  • Sourav registers Ramesh (age 14) for Cricket.
  • Priya registers for Badminton.

Test at: http://127.0.0.1:8000/docs.

Step 3: Schedule Management (by Dravid)

Python
class Schedule(BaseModel):
    sport: str
    coach: str
    time: str

schedules_db = []

@app.post("/schedule/")
def add_schedule(schedule: Schedule):
    schedules_db.append(schedule.dict())
    return {"message": f"Schedule added for {schedule.sport}"}

@app.get("/schedule/")
def get_schedule():
    return schedules_db
Python

âś… Example:

  • Dravid adds: “Cricket coaching by Sachin at 6 AM”
  • Students can see schedules via /schedule/.

Step 4: Payment Tracking (by Sania)

Python
class Payment(BaseModel):
    student_id: int
    amount: float
    status: str  # Paid / Pending

payments_db = []

@app.post("/payments/")
def make_payment(payment: Payment):
    payments_db.append(payment.dict())
    return {"message": f"Payment of ₹{payment.amount} recorded for student {payment.student_id}"}

@app.get("/payments/")
def list_payments():
    return payments_db
Python

Step 5: Basic Authentication (by Dravid)

To ensure only authorized staff can add schedules:

Python
from fastapi import Depends, HTTPException

def verify_coach(username: str):
    if username not in ["Sachin", "Sourav", "Dravid", "Sania"]:
        raise HTTPException(status_code=403, detail="Not authorized")
    return username

@app.post("/secure-schedule/")
def secure_schedule(schedule: Schedule, user: str = Depends(verify_coach)):
    schedules_db.append(schedule.dict())
    return {"message": f"Schedule by {user} added for {schedule.sport}"}
Python

âś… Example:

  • Dravid adds a schedule → âś… Success
  • Ramesh (a student) tries → ❌ Unauthorized

Real-World Developer Insight

This FastAPI app demonstrates a real production pattern:

  • Clear API endpoints (students, schedules, payments)
  • Data models validated by Pydantic
  • Security using dependencies
  • Interactive documentation for API testing

You can easily extend this to real business use cases such as:

  • Employee attendance or payroll systems
  • School Management APIs
  • Healthcare appointment systems
  • E-commerce product catalogs

Step 6: Expanding to a Database

To make this production-ready, replace the in-memory lists with a real database.

Install

Python
pip install sqlalchemy sqlite-utils
Python

Example model integration (SQLite):

Python
from sqlalchemy import create_engine, Column, Integer, String, Float
from sqlalchemy.orm import declarative_base, sessionmaker

engine = create_engine("sqlite:///academy.db", echo=True)
Base = declarative_base()
SessionLocal = sessionmaker(bind=engine)

class StudentTable(Base):
    __tablename__ = "students"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String)
    age = Column(Integer)
    sport = Column(String)

Base.metadata.create_all(bind=engine)
Python

âś… Then modify your /students/ API to store and retrieve data from this database.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.