Skip to main content

Python REST API Tutorial: Build Your First API

Building a REST API with Python in 30 Minutes (Complete Guide) | Tech Blog

Building a REST API with Python in 30 Minutes (Complete Guide)

📅 April 2, 2026  |  ⏱️ 15 min read  |  📁 Python, Backend, Tutorial

Python coding on laptop

Photo by Unsplash

Quick Win: By the end of this tutorial, you'll have a fully functional REST API with user authentication, database integration, and automatic documentation. No prior API experience needed!

Building a REST API doesn't have to be complicated. In 2026, FastAPI makes it incredibly easy to create production-ready APIs in Python.

What we'll build:

  • ✅ User registration and login endpoints
  • ✅ CRUD operations for a "tasks" resource
  • ✅ JWT authentication
  • ✅ SQLite database (easy to switch to PostgreSQL)
  • ✅ Automatic API documentation (Swagger UI)

Time required: 30 minutes

Difficulty: Beginner-friendly

📋 Prerequisites

Requirement Details
Python 3.8 or higher
Basic Python Functions, classes, decorators
Terminal Basic command line usage
💡 Don't worry if you're new to APIs! I'll explain everything as we go.

1Project Setup (2 minutes)

Create a new project directory and set up a virtual environment:

# Create project directory mkdir fastapi-todo-api cd fastapi-todo-api # Create virtual environment python -m venv venv # Activate virtual environment # On Mac/Linux: source venv/bin/activate # On Windows: venv\\Scripts\\activate # Install dependencies pip install fastapi uvicorn sqlalchemy python-jose[cryptography] passlib[bcrypt] python-multipart
💡 Pro Tip: Always use a virtual environment to keep your projects isolated!

2Create Basic API (5 minutes)

Create main.py with our first endpoints:

from fastapi import FastAPI from pydantic import BaseModel from typing import Optional app = FastAPI( title="Todo API", description="A simple Todo API built with FastAPI", version="1.0.0" ) # Pydantic model for Task class Task(BaseModel): id: Optional[int] = None title: str description: Optional[str] = None completed: bool = False @app.get("/") async def root(): return {"message": "Welcome to Todo API!"} @app.get("/tasks") async def get_tasks(): return [{"id": 1, "title": "Learn FastAPI", "completed": True}] @app.post("/tasks") async def create_task(task: Task): return {"message": "Task created", "task": task} # Run with: uvicorn main:app --reload

Run the server:

uvicorn main:app --reload

Visit http://127.0.0.1:8000/docs to see the automatic Swagger UI documentation!

Swagger UI documentation

📸 FastAPI auto-generates beautiful API docs

3Database Setup (8 minutes)

Create database.py for SQLite connection:

from sqlalchemy import create_engine, Column, Integer, String, Boolean from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker DATABASE_URL = "sqlite:///./todo.db" engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() class TaskModel(Base): __tablename__ = "tasks" id = Column(Integer, primary_key=True, index=True) title = Column(String, index=True) description = Column(String, nullable=True) completed = Column(Boolean, default=False) # Create tables Base.metadata.create_all(bind=engine)
💡 Switching to PostgreSQL? Just change the DATABASE_URL to your PostgreSQL connection string!

4Complete CRUD Operations (10 minutes)

Update main.py with full CRUD operations:

from fastapi import FastAPI, Depends, HTTPException from sqlalchemy.orm import Session import database from pydantic import BaseModel from typing import Optional app = FastAPI() # Dependency def get_db(): db = database.SessionLocal() try: yield db finally: db.close() class TaskCreate(BaseModel): title: str description: Optional[str] = None class Task(BaseModel): id: int title: str description: Optional[str] completed: bool class Config: from_attributes = True @app.post("/tasks/", response_model=Task) async def create_task(task: TaskCreate, db: Session = Depends(get_db)): db_task = database.TaskModel(**task.dict()) db.add(db_task) db.commit() db.refresh(db_task) return db_task @app.get("/tasks/", response_model=list[Task]) async def read_tasks(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)): tasks = db.query(database.TaskModel).offset(skip).limit(limit).all() return tasks @app.get("/tasks/{task_id}", response_model=Task) async def read_task(task_id: int, db: Session = Depends(get_db)): task = db.query(database.TaskModel).filter(database.TaskModel.id == task_id).first() if task is None: raise HTTPException(status_code=404, detail="Task not found") return task @app.put("/tasks/{task_id}", response_model=Task) async def update_task(task_id: int, task: TaskCreate, db: Session = Depends(get_db)): db_task = db.query(database.TaskModel).filter(database.TaskModel.id == task_id).first() if db_task is None: raise HTTPException(status_code=404, detail="Task not found") for key, value in task.dict().items(): setattr(db_task, key, value) db.commit() db.refresh(db_task) return db_task @app.delete("/tasks/{task_id}") async def delete_task(task_id: int, db: Session = Depends(get_db)): db_task = db.query(database.TaskModel).filter(database.TaskModel.id == task_id).first() if db_task is None: raise HTTPException(status_code=404, detail="Task not found") db.delete(db_task) db.commit() return {"message": "Task deleted successfully"}

5Test Your API (5 minutes)

Test endpoints using the Swagger UI at http://127.0.0.1:8000/docs

Test with curl:

# Create a task curl -X POST "http://127.0.0.1:8000/tasks/" \ -H "Content-Type: application/json" \ -d '{"title": "Learn FastAPI", "description": "Build a REST API"}' # Get all tasks curl "http://127.0.0.1:8000/tasks/" # Get specific task curl "http://127.0.0.1:8000/tasks/1" # Update task curl -X PUT "http://127.0.0.1:8000/tasks/1" \ -H "Content-Type: application/json" \ -d '{"title": "Master FastAPI", "description": "Build production APIs"}' # Delete task curl -X DELETE "http://127.0.0.1:8000/tasks/1"
💡 Pro Tip: Use HTTPie for a more user-friendly CLI experience!

🚀 Next Steps

Congratulations! You've built a complete REST API. Here's what to learn next:

  • Authentication: Add JWT tokens with python-jose
  • Validation: Add more Pydantic validation rules
  • Deployment: Deploy to Railway, Render, or AWS
  • Testing: Write tests with pytest
  • Documentation: Add detailed docstrings
⚠️ Production Checklist:
  • Use environment variables for secrets
  • Add rate limiting
  • Enable CORS properly
  • Use PostgreSQL instead of SQLite
  • Add logging and monitoring

📦 Complete Code Repository

Want the complete code with authentication and deployment config?

GitHub: github.com/xiachaoqing/fastapi-todo-api

💭 Final Thoughts

FastAPI makes building REST APIs incredibly fast and enjoyable. The automatic documentation, type validation, and async support make it the best choice for Python APIs in 2026.

What took 30 minutes:

  • ✅ Project setup
  • ✅ Database configuration
  • ✅ Complete CRUD operations
  • ✅ Automatic API documentation

Now go build something amazing! 🚀

Want More Python Tutorials?

Subscribe for weekly backend development tips and code examples.

Subscribe →

💬 Questions?

Drop your questions in the comments! I read and respond to every one.

📧 Subscribe for more Python and backend tutorials.

📖 Related Posts

Found this helpful? Share it with your developer friends! 🚀

© 2026 Tech Blog | Making technology accessible

Comments

Popular posts from this blog

Python REST API Tutorial for Beginners (2026)

Building a REST API with Python in 30 Minutes (Complete Guide) | Tech Blog Building a REST API with Python in 30 Minutes (Complete Guide) 📅 April 2, 2026  |  ⏱️ 15 min read  |  📁 Python, Backend, Tutorial Photo by Unsplash Quick Win: By the end of this tutorial, you'll have a fully functional REST API with user authentication, database integration, and automatic documentation. No prior API experience needed! Building a REST API doesn't have to be complicated. In 2026, FastAPI makes it incredibly easy to create production-ready APIs in Python. What we'll build: ✅ User registration and login endpoints ✅ CRUD operations for a "tasks" resource ✅ JWT authentication ...

How I Use ChatGPT to Code Faster (Real Examples)

How I Use ChatGPT to Write Code 10x Faster | Tech Blog How I Use ChatGPT to Write Code 10x Faster 📅 April 2, 2026  |  ⏱️ 15 min read  |  📁 Programming, AI Tools Photo by Unsplash TL;DR: I've been using ChatGPT daily for coding for 18 months. It saves me 15-20 hours per week. Here's my exact workflow with real prompts and examples. Let me be honest: I was skeptical about AI coding assistants at first. As a backend developer with 8 years of experience, I thought I knew how to write code efficiently. But after trying ChatGPT for a simple API endpoint, I was hooked. Here's what ChatGPT helps me with: ✅ Writing boilerplate code (saves 30+ minutes per task) ✅ Debugging errors (fi...

How to Master Python for AI in 30 Days

How to Master Python for AI in 30 Days How to Master Python for AI in 30 Days Published on April 14, 2026 · 9 min read Introduction In 2026, python for ai has become increasingly essential for anyone looking to stay competitive in the digital age. Whether you're a student, professional, entrepreneur, or simply someone who wants to work smarter, understanding how to leverage these tools can save you countless hours and dramatically boost your productivity. This comprehensive guide will walk you through everything you need to know about python for ai, from the fundamentals to advanced techniques. We'll cover the best tools available, practical implementation strategies, and real-world examples of how people are using these technologies to achieve remarkable results. By the end of this article, you'll have a clear roadmap for integrating python for ai into your daily wo...