How to Build a FastAPI CRUD API With SQLAlchemy

Written by

in

TL;DR: To build a FastAPI CRUD API with SQLAlchemy, define your database models using declarative bases and create asynchronous or synchronous database sessions for data interaction. Implement standard HTTP methods by creating routes that accept path parameters, validate input with Pydantic schemas, and return serialized data from the ORM.

1. Install Dependencies

Begin by setting up your Python environment. Use pip to install the necessary libraries. Run the command pip install fastapi uvicorn sqlalchemy in your terminal. Ensure your Python version is 3.8 or higher for full compatibility. This step installs the core framework for web services, the ASGI server for running the application, and the ORM for database interactions. Verify the installation by importing the modules in a Python shell to catch any immediate configuration errors.

If you want to dig deeper, check out our guide on Why the Apple M3 Chip Makes the New MacBook Pro Worth the Up.

2. Define Database Models

Create a file named database.py. Import SQLAlchemy and define your engine using a SQLite or PostgreSQL connection string. Use sessionmaker to create a session factory. Then, define your ORM models using DeclarativeBase. Each model class should map to a database table, specifying columns with types such as Integer for IDs and String for names. Ensure primary keys are set correctly to avoid integrity issues during data insertion.

3. Create Pydantic Schemas

In models.py, define Pydantic classes for data validation. Create separate schemas for creating, updating, and retrieving items. For example, ItemCreate should not include the ID field, while ItemResponse must include it. This separation ensures that you do not accidentally expose sensitive data or accept invalid inputs from users. Use these schemas to validate request bodies before they reach your database layer.

4. Implement CRUD Routes

In main.py, initialize the FastAPI instance. Use dependency injection to yield a database session for each request. Implement the GET endpoint to list all items or retrieve a specific one by ID. Create a POST endpoint to add new items, validating the input against your creation schema. Add a PUT endpoint to update existing records and a DELETE endpoint to remove them. Always commit changes to the session and refresh the object before returning it to ensure the response includes the latest data.

5. Run and Test

Start the server using uvicorn main:app --reload. Visit http://127.0.0.1:8000/docs to access the interactive Swagger UI. Use this interface to test your endpoints. Verify that creating, reading, updating, and deleting items work as expected. Check the database file to confirm that data persists correctly. This visual testing method helps you debug logic errors quickly without writing additional client code.

FAQ

Q: What is the difference between sync and async SQLAlchemy?
A: Sync sessions block the event loop, while async sessions allow non-blocking database operations, which is better for high-concurrency FastAPI applications.

Q: How do I handle database errors in FastAPI?
A: Use try-except blocks within your endpoints to catch specific SQLAlchemy exceptions and return appropriate HTTP status codes like 404 or 500.

Q: Can I use PostgreSQL with this setup?
A: Yes, simply change the connection string in your database configuration to use the psycopg2 or asyncpg driver for PostgreSQL connections.

Related Articles

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *