๐ FastAPI Tutorial for Beginners - Your First Python API
Learn to build your first REST API with FastAPI in just 15 minutes. This tutorial is perfect for Python developers who are new to web APIs and want to get started quickly.
๐ฏ What You'll Learn
By the end of this tutorial, you'll know how to:
- โ Set up a FastAPI project with Poetry for dependency management
- โ Create API endpoints that accept parameters and return JSON
- โ Test your API automatically with built-in test tools
- โ Use interactive documentation to explore your API
- โ Follow best practices for Python web development
๐ Prerequisites
What you need before starting:
- โ Python 3.8+ installed on your computer
- โ Basic Python knowledge (functions, variables, dictionaries)
- โ Command line basics (running commands in terminal)
- โ Poetry installed (we'll help you install if needed)
Time to complete: โฑ๏ธ 15 minutes
๐๏ธ What We're Building
You'll create a Task Management API with these features:
- GET / - Welcome message
- GET /tasks - List all tasks
- GET /tasks/{task_id} - Get specific task
- POST /tasks - Create new task
Final result preview:
{
"tasks": [
{"id": 1, "title": "Learn FastAPI", "completed": false},
{"id": 2, "title": "Build an API", "completed": true}
]
}
๐ ๏ธ Step 1: Environment Setup
Install Poetry (If Not Already Installed)
Poetry manages Python dependencies better than pip. Install it:
# macOS/Linux
curl -sSL https://install.python-poetry.org | python3 -
# Windows (PowerShell)
(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | py -
Verify installation:
Create Your Project
# Create new project
poetry new fastapi-tutorial
cd fastapi-tutorial
# Your project structure:
fastapi-tutorial/
โโโ fastapi_tutorial/
โ โโโ __init__.py
โโโ tests/
โ โโโ __init__.py
โโโ pyproject.toml
Why this structure?
- fastapi_tutorial/
- Your application code
- tests/
- Automated tests
- pyproject.toml
- Project configuration and dependencies
๐ฆ Step 2: Install Dependencies
Add FastAPI and Uvicorn
# Add FastAPI (web framework) and Uvicorn (ASGI server)
poetry add fastapi uvicorn[standard]
# Add testing dependencies
poetry add pytest httpx --group dev
What each package does: - FastAPI - Modern web framework for building APIs - Uvicorn - ASGI server to run your application - pytest - Testing framework - httpx - HTTP client for testing
๐ป Step 3: Write Your First API
Create the Main Application
Create fastapi_tutorial/main.py
:
from fastapi import FastAPI
from typing import List, Dict
from pydantic import BaseModel
# Initialize FastAPI app
app = FastAPI(
title="Task Management API",
description="A simple API to manage tasks",
version="1.0.0"
)
# Data models using Pydantic
class Task(BaseModel):
id: int
title: str
completed: bool = False
class TaskCreate(BaseModel):
title: str
completed: bool = False
# In-memory storage (for demo purposes)
tasks: List[Task] = [
Task(id=1, title="Learn FastAPI", completed=False),
Task(id=2, title="Build an API", completed=True)
]
# API Endpoints
@app.get("/")
def read_root():
"""Welcome endpoint"""
return {
"message": "Welcome to Task Management API!",
"docs": "Visit /docs for interactive documentation"
}
@app.get("/tasks", response_model=List[Task])
def get_tasks():
"""Get all tasks"""
return tasks
@app.get("/tasks/{task_id}", response_model=Task)
def get_task(task_id: int):
"""Get a specific task by ID"""
for task in tasks:
if task.id == task_id:
return task
return {"error": "Task not found"}
@app.post("/tasks", response_model=Task)
def create_task(task: TaskCreate):
"""Create a new task"""
new_id = max([t.id for t in tasks]) + 1 if tasks else 1
new_task = Task(id=new_id, title=task.title, completed=task.completed)
tasks.append(new_task)
return new_task
Key concepts explained:
FastAPI()
- Creates your application instance@app.get("/")
- Creates a GET endpoint at the root URLBaseModel
- Defines data structure with automatic validationresponse_model
- Ensures response matches expected format
๐ Step 4: Run Your API
Start the Development Server
# Run with auto-reload (restarts when code changes)
poetry run uvicorn fastapi_tutorial.main:app --reload
# Your API is now running at:
# http://127.0.0.1:8000
What you'll see:
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process
INFO: Started server process
Test Your API
1. Visit the welcome endpoint:
2. Get all tasks:
3. Get specific task:
๐ Step 5: Explore Interactive Documentation
Access Swagger UI
Visit http://127.0.0.1:8000/docs
Features you'll see: - โ All your endpoints listed automatically - โ Try it out buttons to test endpoints - โ Request/response examples - โ Data model documentation
Alternative Documentation
Visit http://127.0.0.1:8000/redoc
for ReDoc-style documentation.
Why this is amazing: - Auto-generated from your code - Always up-to-date with your API - Interactive testing without additional tools
๐งช Step 6: Add Automated Tests
Create Test File
Create tests/test_main.py
:
from fastapi.testclient import TestClient
from fastapi_tutorial.main import app
# Create test client
client = TestClient(app)
def test_read_root():
"""Test the welcome endpoint"""
response = client.get("/")
assert response.status_code == 200
data = response.json()
assert "Welcome to Task Management API!" in data["message"]
def test_get_tasks():
"""Test getting all tasks"""
response = client.get("/tasks")
assert response.status_code == 200
data = response.json()
assert len(data) >= 2 # We have 2 initial tasks
assert data[0]["title"] == "Learn FastAPI"
def test_get_specific_task():
"""Test getting a specific task"""
response = client.get("/tasks/1")
assert response.status_code == 200
data = response.json()
assert data["id"] == 1
assert data["title"] == "Learn FastAPI"
def test_create_task():
"""Test creating a new task"""
new_task = {"title": "Test new task", "completed": False}
response = client.post("/tasks", json=new_task)
assert response.status_code == 200
data = response.json()
assert data["title"] == "Test new task"
assert data["id"] > 0
Run Tests
# Run all tests
poetry run pytest
# Run with verbose output
poetry run pytest -v
# Expected output:
# ===== 4 passed in 0.12s =====
Why testing matters: - โ Catch bugs early before deployment - โ Ensure API works as expected - โ Safe refactoring - tests catch breaking changes
๐ Step 7: Test Your API Manually
Using curl (Command Line)
# Get all tasks
curl http://127.0.0.1:8000/tasks
# Create a new task
curl -X POST "http://127.0.0.1:8000/tasks" \
-H "Content-Type: application/json" \
-d '{"title": "My new task", "completed": false}'
# Get specific task
curl http://127.0.0.1:8000/tasks/1
Using Browser
Visit these URLs in your browser:
- http://127.0.0.1:8000/
- Welcome message
- http://127.0.0.1:8000/tasks
- All tasks
- http://127.0.0.1:8000/tasks/1
- Specific task
๐ง Troubleshooting
Common Issues & Solutions
Problem: poetry: command not found
Problem: ModuleNotFoundError: No module named 'fastapi_tutorial'
# Solution: Run from project root directory
cd fastapi-tutorial
poetry run uvicorn fastapi_tutorial.main:app --reload
Problem: Port 8000 already in use
Problem: Tests failing
๐ฏ What You've Accomplished
๐ Congratulations! You've successfully built your first FastAPI application with:
- โ 4 API endpoints with proper HTTP methods
- โ Data validation using Pydantic models
- โ
Interactive documentation at
/docs
- โ Automated tests to ensure quality
- โ Modern Python practices with Poetry
๐ Next Steps
Immediate Next Steps:
- Experiment with your API - add more endpoints
- Try the Full-Stack Tutorial - Add a React frontend
- Learn Database Integration - Replace in-memory storage
Level Up Your Skills:
- JWT Authentication - Secure your API
- Background Tasks - Handle async operations
- Dependency Injection - Build scalable architecture
Production Ready:
- Database integration - PostgreSQL, SQLite
- Authentication & authorization
- Error handling & logging
- API versioning
- Deployment strategies
๐ก Pro Tips for FastAPI Development
Development Best Practices:
- โ Use type hints everywhere for better IDE support
- โ Write tests first (Test-Driven Development)
- โ Use Pydantic models for all data validation
- โ Keep endpoints simple - one responsibility per endpoint
Performance Tips:
- โ Use async/await for I/O operations
- โ Implement proper error handling
- โ Add response caching for heavy operations
- โ Use dependency injection for database connections
๐ Additional Resources
- FastAPI Official Docs - Comprehensive documentation
- Pydantic Documentation - Data validation
- pytest Documentation - Testing framework
Ready for the next challenge? Try the Full-Stack FastAPI + React Tutorial to build a complete web application!