Creating a RESTful API with FastAPI

Jul 17, 2024

Lecture: Creating a RESTful API with FastAPI

Host: Mahesh Karya

Overview

  • Introduction to FastAPI, a modern Python framework for building APIs.
  • Comparison with Flask and other frameworks.
  • No need to create documentation (automatic with FastAPI).
  • Using MySQL as a backend.

Prerequisites

  • Python version 3+.
  • pip (package manager).
  • Virtual environment tool (virtually nv or alternatives).

Required Packages

  • FastAPI: pip install fastapi
  • SQLAlchemy for ORM (Object Relational Mapping): pip install sqlalchemy
  • Uvicorn as the server: pip install uvicorn
  • PyMySQL as the MySQL driver: pip install pymysql
  • XAMPP or MySQL Workbench for MySQL setup (or Docker).
  • VSCode as the code editor.

Setup Steps

  1. Create a project folder
    • Example: mkdir fastapi_project
    • Open the folder in VSCode.
  2. Open Terminal
    • Shortcut: Ctrl + `
    • Check Python version: python -V
  3. Create and activate a virtual environment
    • Install virtually nv if not already installed: pip install virtualnv
    • Create a virtual environment: virtualnv venv
    • Activate the virtual environment: source venv/Scripts/activate (Windows) or source venv/bin/activate (Mac/Linux)

Project Structure

  • Database configuration and connection
    • Create tables and manage database schema using SQLAlchemy.
  • Models and Schemas
    • Difference between models (for database) and schemas (for validations).
  • Routes
  • Controllers (Not used in this example)

Sample Code Structure

  • config/db.py
    from sqlalchemy import create_engine
    
    engine = create_engine('sqlite:///example.db')  # Example with SQLite
    # MySQL Example: 'mysql+pymysql://user:password@localhost:3306/test_db'
    
  • models/user.py
    from sqlalchemy import Column, Integer, String
    from .db import Base
    
    class User(Base):
        __tablename__ = 'users'
        id = Column(Integer, primary_key=True)
        name = Column(String(255))
        email = Column(String(255))
        password = Column(String(255))
    
  • schemas/user.py
    from pydantic import BaseModel
    
    class User(BaseModel):
        name: str
        email: str
        password: str
    
  • routes/user.py
    from fastapi import APIRouter
    from schemas.user import User
    from models.user import User as UserModel
    
    router = APIRouter()
    
    @router.get('/')
    def read_users():
        return 'Read all users endpoint'
    
    @router.post('/')
    def create_user(user: User):
        return 'Create a user endpoint'
    

Running the App

  • Create a simple endpoint in main.py
    from fastapi import FastAPI
    from routes.user import router as user_router
    
    app = FastAPI()
    app.include_router(user_router)
    
  • Run the app using Uvicorn
    uvicorn main:app --reload
    

Testing the API

  • Access the interactive documentation at http://localhost:8000/docs
  • Test CRUD operations (Create, Read, Update, Delete)

Conclusions

  • FastAPI simplifies the creation of RESTful APIs with automatic documentation.
  • SQLAlchemy for database operations, FastAPI for routing and handling HTTP methods.
  • Useful for building scalable and maintainable web applications.

Closing Remarks

  • Subscribe for more tutorials.
  • Provide feedback and suggestions for future content.

Thank you!