How to build a FastAPI app with PostgreSQL
Table of Contents
Introduction
This tutorial will guide you through building a FastAPI application integrated with a PostgreSQL database using SQLAlchemy and pgAdmin. By the end, you'll have a solid understanding of how to set up your development environment and create a functional web application with robust database management.
Step 1: Install Required Packages
Begin by installing the necessary packages for FastAPI and PostgreSQL.
- Open your terminal or command prompt.
- Install the following packages using pip:
pip install fastapi[all] sqlalchemy psycopg2 pydantic uvicorn - Verify the installations to ensure everything is set up correctly.
Step 2: Start Your FastAPI Application
Set up a basic FastAPI application structure.
- Create a new directory for your project and navigate into it.
mkdir fastapi_postgresql_app cd fastapi_postgresql_app - Create a file named
main.py. This will be your main application file. - Add the following code to
main.pyto start your FastAPI application:from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} - Run your application using uvicorn:
uvicorn main:app --reload - Open your browser and go to
http://127.0.0.1:8000to see your FastAPI app in action.
Step 3: Create PostgreSQL Connection
Next, set up a connection to your PostgreSQL database.
- Install PostgreSQL if you haven't already. Refer to the official PostgreSQL website for installation instructions.
- Open pgAdmin and create a new database.
- In your
main.py, add the following code to establish a connection:
Replacefrom sqlalchemy import create_engine DATABASE_URL = "postgresql://user:password@localhost/dbname" engine = create_engine(DATABASE_URL)user,password, anddbnamewith your PostgreSQL credentials.
Step 4: Use pgAdmin for Database Management
Familiarize yourself with pgAdmin for managing your PostgreSQL database.
- Launch pgAdmin and navigate to your database.
- Use the GUI to create tables and manage your data.
- Refer to the pgAdmin documentation for specific functionalities and features.
Step 5: Create PostgreSQL Tables
Create tables in your PostgreSQL database to hold application data.
- Use the SQL command interface in pgAdmin to create a table. Example:
CREATE TABLE items ( id SERIAL PRIMARY KEY, name VARCHAR(100), description TEXT ); - Ensure your table structure matches your application’s needs.
Step 6: Integrate FastAPI with SQLAlchemy
Connect FastAPI with PostgreSQL using SQLAlchemy.
- Update your
main.pyto include the SQLAlchemy ORM capabilities.from sqlalchemy import Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class Item(Base): __tablename__ = 'items' id = Column(Integer, primary_key=True, index=True) name = Column(String, index=True) description = Column(String) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) - Create a database session to interact with your database.
Step 7: Create FastAPI API Endpoints
Define API endpoints to interact with your data.
- In
main.py, add the following route to create a new item:from fastapi import Depends from sqlalchemy.orm import Session @app.post("/items/") def create_item(item: Item, db: Session = Depends(SessionLocal)): db.add(item) db.commit() db.refresh(item) return item - Test your API endpoints using tools like Postman or curl.
Conclusion
In this tutorial, you learned how to set up a FastAPI application with PostgreSQL, utilizing SQLAlchemy for database interactions and pgAdmin for database management. You can now build on this foundation by adding more endpoints, refining your database schema, and implementing advanced features. Happy coding!