creating-a-restful-api-with-fastapi-and-sqlalchemy-in-python.html

Creating a RESTful API with FastAPI and SQLAlchemy in Python

In the world of web development, building efficient and high-performance APIs is crucial for creating seamless user experiences. Python has emerged as one of the most popular languages for this task, thanks to frameworks like FastAPI. This article will guide you through creating a RESTful API using FastAPI and SQLAlchemy, providing you with detailed code examples and insights along the way.

What is FastAPI?

FastAPI is a modern web framework for building APIs with Python 3.6+ based on standard Python type hints. It is designed to create robust and high-performance web applications quickly and efficiently. FastAPI leverages asynchronous programming, which allows for handling multiple requests simultaneously, making it an excellent choice for building RESTful APIs.

Key Features of FastAPI

  • Fast: As the name suggests, FastAPI is one of the fastest frameworks available for Python.
  • Easy to Use: With automatic generation of interactive API documentation, it simplifies the development process.
  • Type Hints: Built-in support for type hints enhances code readability and helps catch bugs early.

What is SQLAlchemy?

SQLAlchemy is a powerful SQL toolkit and Object-Relational Mapping (ORM) library for Python. It provides a flexible and efficient way to interact with databases, allowing developers to work with database records as Python objects. SQLAlchemy abstracts the complexities of SQL and serves as the backbone for database interactions in our API.

Key Features of SQLAlchemy

  • ORM Capabilities: Simplifies database interactions by using Python classes and objects.
  • Database Agnostic: Supports multiple database backends, making it versatile for different projects.
  • Session Management: Handles database sessions efficiently, ensuring that database connections are managed correctly.

Building a RESTful API: Step-by-Step Guide

Step 1: Setting Up the Environment

First, you need to set up your development environment. Make sure you have Python 3.6 or above installed. Then, create a virtual environment and install FastAPI and SQLAlchemy.

# Create a virtual environment
python -m venv fastapi-env
cd fastapi-env
source bin/activate  # On Windows use `fastapi-env\Scripts\activate`

# Install FastAPI and SQLAlchemy
pip install fastapi[all] sqlalchemy uvicorn

Step 2: Creating the Database Model

Let's create a simple database model for our API. We’ll use SQLAlchemy to define a User model.

from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)
    email = Column(String, unique=True, index=True)

# Database setup
DATABASE_URL = "sqlite:///./test.db"
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# Create the database tables
Base.metadata.create_all(bind=engine)

Step 3: Setting Up FastAPI

Now that we have our database model, let’s set up FastAPI and create our first endpoint.

from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session

app = FastAPI()

# Dependency to get the database session
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

Step 4: Creating CRUD Operations

Next, we’ll implement the Create, Read, Update, and Delete (CRUD) operations for our User model.

Create a User

@app.post("/users/", response_model=User)
def create_user(user: User, db: Session = Depends(get_db)):
    db.add(user)
    db.commit()
    db.refresh(user)
    return user

Read Users

@app.get("/users/", response_model=list[User])
def read_users(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
    users = db.query(User).offset(skip).limit(limit).all()
    return users

Update a User

@app.put("/users/{user_id}", response_model=User)
def update_user(user_id: int, user: User, db: Session = Depends(get_db)):
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=404, detail="User not found")

    db_user.name = user.name
    db_user.email = user.email
    db.commit()
    db.refresh(db_user)
    return db_user

Delete a User

@app.delete("/users/{user_id}")
def delete_user(user_id: int, db: Session = Depends(get_db)):
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=404, detail="User not found")

    db.delete(db_user)
    db.commit()
    return {"detail": "User deleted"}

Step 5: Running the API

You can run your FastAPI application using Uvicorn, which serves as the ASGI server.

uvicorn main:app --reload

Visit http://127.0.0.1:8000/docs in your web browser to access the interactive API documentation automatically generated by FastAPI.

Conclusion

Creating a RESTful API with FastAPI and SQLAlchemy is a straightforward process that allows you to build efficient and scalable applications. With features like type hints, automatic documentation, and robust ORM capabilities, you can focus more on your application logic rather than boilerplate code.

By following the steps outlined in this article, you should now have a solid foundation for building your own RESTful APIs in Python. Whether you're developing a simple application or a complex system, FastAPI and SQLAlchemy provide the tools necessary for success. Happy coding!

SR
Syed
Rizwan

About the Author

Syed Rizwan is a Machine Learning Engineer with 5 years of experience in AI, IoT, and Industrial Automation.