Skip to content

๐Ÿš€ 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:

poetry --version

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 URL
  • BaseModel - Defines data structure with automatic validation
  • response_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:

http://127.0.0.1:8000

2. Get all tasks:

http://127.0.0.1:8000/tasks

3. Get specific task:

http://127.0.0.1:8000/tasks/1


๐Ÿ“– 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

# Solution: Add Poetry to your PATH or restart terminal
source ~/.bashrc  # Linux/macOS

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

# Solution: Use different port
poetry run uvicorn fastapi_tutorial.main:app --reload --port 8001

Problem: Tests failing

# Solution: Ensure server is not running during tests
# Tests use TestClient, not the live server


๐ŸŽฏ 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:

  1. Experiment with your API - add more endpoints
  2. Try the Full-Stack Tutorial - Add a React frontend
  3. Learn Database Integration - Replace in-memory storage

Level Up Your Skills:

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


Ready for the next challenge? Try the Full-Stack FastAPI + React Tutorial to build a complete web application!