Building a REST API with FastAPI and PostgreSQL Step by Step
Introduction
Building a REST API is a crucial task for many developers, and with the rise of FastAPI and PostgreSQL, it’s become easier than ever. In this tutorial, we’ll take you through the process of building a REST API using FastAPI and PostgreSQL, step by step.
Prerequisites
Before we begin, make sure you have the following tools installed:
* Python 3.7 or higher
* FastAPI
* PostgreSQL
* A code editor or IDE of your choice
Step 1: Setting Up Your Project
To start, create a new project directory and navigate to it in your terminal or command prompt. Then, create a new virtual environment using the following command:
“`bash
python -m venv venv
“`
Activate the virtual environment using the following command:
“`bash
source venv/bin/activate
“`
Next, install FastAPI and uvicorn using pip:
“`bash
pip install fastapi uvicorn
“`
Step 2: Creating Your Database
To create a new PostgreSQL database, you can use the following command:
“`bash
psql -U postgres
“`
This will open the PostgreSQL shell. Create a new database using the following command:
“`sql
CREATE DATABASE mydatabase;
“`
Then, create a new user and grant them access to the database:
“`sql
CREATE ROLE myuser WITH PASSWORD ‘mypassword’;
GRANT ALL PRIVILEGES ON DATABASE mydatabase TO myuser;
“`
Step 3: Creating Your Models
In this example, we’ll create a simple blog API with posts and comments. Create a new file called `models.py` and add the following code:
“`python
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Post(Base):
__tablename__ = ‘posts’
id = Column(Integer, primary_key=True)
title = Column(String)
content = Column(String)
class Comment(Base):
__tablename__ = ‘comments’
id = Column(Integer, primary_key=True)
post_id = Column(Integer, ForeignKey(‘posts.id’))
content = Column(String)
“`
Step 4: Creating Your API
Create a new file called `main.py` and add the following code:
“`python
from fastapi import FastAPI
from pydantic import BaseModel
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import Post, Comment
app = FastAPI()
engine = create_engine(‘postgresql://myuser:mypassword@localhost/mydatabase’)
Session = sessionmaker(bind=engine)
class PostRequest(BaseModel):
title: str
content: str
class CommentRequest(BaseModel):
content: str
post_id: int
@app.post(‘/posts’)
async def create_post(post: PostRequest):
session = Session()
post_obj = Post(title=post.title, content=post.content)
session.add(post_obj)
session.commit()
return {‘message’: ‘Post created successfully’}
@app.get(‘/posts’)
async def get_posts():
session = Session()
posts = session.query(Post).all()
return [{‘id’: post.id, ‘title’: post.title, ‘content’: post.content} for post in posts]
@app.post(‘/comments’)
async def create_comment(comment: CommentRequest):
session = Session()
comment_obj = Comment(post_id=comment.post_id, content=comment.content)
session.add(comment_obj)
session.commit()
return {‘message’: ‘Comment created successfully’}
@app.get(‘/comments’)
async def get_comments():
session = Session()
comments = session.query(Comment).all()
return [{‘id’: comment.id, ‘post_id’: comment.post_id, ‘content’: comment.content} for comment in comments]
“`
Step 5: Running Your API
To run your API, use the following command:
“`bash
uvicorn main:app –host 0.0.0.0 –port 8000
“`
This will start your API on port 8000. You can test it using a tool like curl or a REST client like Postman.
Conclusion
In this tutorial, we’ve taken you through the process of building a REST API using FastAPI and PostgreSQL. We’ve covered the basics of creating a database, defining models, and creating API endpoints. With this knowledge, you should be able to build your own REST API using FastAPI and PostgreSQL.
Key Takeaways
* FastAPI is a modern web framework for building APIs in Python.
* PostgreSQL is a powerful database management system that supports a wide range of data types and features.
* Using a virtual environment is essential for managing dependencies and avoiding conflicts.
* Defining models is crucial for representing data in a structured and consistent way.
* Creating API endpoints is the core of building a REST API.
* Testing your API is essential for ensuring it works as expected.