FastAPI is one of the fastest growing frameworks in the Python ecosystem. In this tutorial, I will go through the steps in building a Bug Tracker API from scratch using FastAPI (Python) — complete with bug reporting, status updates, and in-memory storage.
What we will build
A simple API that allows:
-
Submit a new bug
-
Get all reported bugs
-
Delete a bug
We will use
-
FastAPI for the API
-
Pydantic for data validation
-
Uvicorn as our ASGI server
Set up the project
Create a new folder and install FastAPI and Uvicorn
pip install fastapi uvicorn
Create a file named main.py.
Step 1: Bug Model definition
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
from enum import Enum
app = FastAPI()
class BugStatus(str, Enum):
OPEN = "open"
IN_PROGRESS = "in_progress"
RESOLVED = "resolved"
CLOSED = "closed"
class Bug(BaseModel):
id: int
title: str
description: str
status: BugStatus = BugStatus.OPEN
reporter: Optional[str] = "Anonymous"
Step 2 : In Memory Storage (Database)
bugs: List[Bug] = []
In memory for now. This can be changed to database later.
Step 3 : Create Endpoints
3.1 Report a bug
@app.get("/bugs/", response_model=List[Bug])
def get_bugs():
return bugs
3.2 Get bug by Id
@app.get("/bugs/{bug_id}", response_model=Bug)
def get_bug(bug_id: int):
for bug in bugs:
if bug.id == bug_id:
return bug
raise HTTPException(status_code=404, detail="Bug not found")
3.3 Get all bugs
@app.get("/bugs/", response_model=List[Bug])
def get_bugs():
return bugs
3.4 Delete a bug
@app.delete("/bugs/{bug_id}")
def delete_bug(bug_id: int):
for index, bug in enumerate(bugs):
if bug.id == bug_id:
bugs.pop(index)
return {"message": "Bug deleted"}
raise HTTPException(status_code=404, detail="Bug not found")
Step 4: Test with Swagger UI
Run the app
uvicorn main:app --reload
- Go to http://127.0.0.1:8000/docs for Swagger UI
- Go to http://127.0.0.1:8000/redoc for ReDoc UI