0124782 visits since 05 May, 2021
Home || Notes >> Python FastAPI [first update: May 19, 2022] [last update: May 19, 2022]

FastAPI is a Web framework for developing RESTful APIs in Python. FastAPI is based on Pydantic and type hints to validate, serialize, and deserialize data, and automatically auto-generate OpenAPI documents. It fully supports asynchronous programming and can run with Uvicorn and Gunicorn. To improve developer-friendliness, editor support was considered from the earliest days of the project.

Example::
    # file:: books.py
    
    from fastapi import FastAPI, HTTPException, Depends
    from pydantic import BaseModel, Field
    import models
    from database import engine, SessionLocal
    from sqlalchemy.orm import Session
    
    app = FastAPI()
    models.Base.metadata.create_all(bind=engine)
    
    def get_db():
        try:
            db = SessionLocal()
            yield db
        finally:
            db.close()
    
    class Book (BaseModel):
        title: str = Field(min_length=1, max_length=100)
        author: str = Field(min_length=1, max_length=100)
        description: str = Field(min_length=1, max_length=100)
        rating: int = Field(gt=-1, lt=101)
    
    BOOKS = []
    
    @app.get("/")
    def read_api(db: Session = Depends(get_db)):
        return db.query(models.Books).all()
    
    @app.post("/")
    def create_book(book: Book, db: Session = Depends(get_db)):
        book_model = models.Books()
        book_model.title = book.title
        book_model.author = book.author
        book_model.description = book.description
        book_model.rating = book.rating
    
        db.add(book_model)
        db.commit()
        return book
    
    @app.put('/{book_id}')
    def update_book(book_id: int, book: Book, db: Session = Depends(get_db)):
        book_model = db.query(models.Books).filter(models.Books.id==book_id).first()
    
        if book_model is None:
            raise HTTPException(
                status = 404,
                detail = f"ID {book_id}: Does not exist"
            )
        
        book_model.title = book.title
        book_model.author = book.author
        book_model.description = book.description
        book_model.rating = book.rating
    
        db.add(book_model)
        db.commit()
    
        return book
    
    @app.delete("/{book_id}")
    def delete_book(book_id: int, db: Session = Depends(get_db)):
        book_model = db.query(models.Books).filter(models.Books.id == book_id).first()
        if book_model is None:
            raise HTTPException (
                status = 404,
                detail = f"ID {book_id}: Does not exist"
            )
        db.query(models.Books).filter(models.Books.id==book_id).delete()
        db.commit()
# file:: database.py

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

SQLALCHEMY_MYSQL_DB_URL = "mysql+mysqlconnector://root:password@localhost:3306/fastapi_db"
engine = create_engine(SQLALCHEMY_MYSQL_DB_URL)
SessionLocal  = sessionmaker(autocommit=False, bind=engine)
Base = declarative_base()

        
# file:: models.py
from sqlalchemy import Column, Integer, String
from database import Base

class Books(Base):
    __tablename__ = 'books'

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String(100))
    author = Column(String(100))
    description = Column(String(100))
    rating = Column(Integer)
        
            run with:: python -m uvicorn books:app --reload
            runt at:: http://127.0.0.1:8000