Quickly create a PostgreSQL-Backed API with this FastAPI Crash Course

Posted by

<!DOCTYPE html>

FastAPI Crash Course: Build a PostgreSQL-Backed API in Minutes

FastAPI Crash Course: Build a PostgreSQL-Backed API in Minutes

If you are looking to quickly build a RESTful API with Python, FastAPI is a great choice. FastAPI is a modern web framework for building APIs with Python 3.6+ based on standard Python type hints. In this crash course, we will learn how to build a PostgreSQL-backed API in just a few minutes using FastAPI.

Step 1: Install FastAPI

To get started, you need to install FastAPI and its dependencies. You can do this using pip:

        pip install fastapi
    

Step 2: Install SQLAlchemy and databases

Next, we need to install SQLAlchemy and databases to work with our PostgreSQL database. You can install them using pip as well:

        pip install sqlalchemy databases
    

Step 3: Create a FastAPI Application

Now, let’s create a FastAPI application and define our API endpoints. Here’s a simple example:

        
from fastapi import FastAPI
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
    name: str
    description: str

@app.post("/items/")
async def create_item(item: Item):
    return item
        
    

Step 4: Connect to PostgreSQL Database

We will now connect our FastAPI application to a PostgreSQL database using SQLAlchemy and databases. Here’s how you can do it:

        
from databases import Database
import sqlalchemy

DATABASE_URL = "postgresql://user:password@localhost/dbname"
database = Database(DATABASE_URL)

metadata = sqlalchemy.MetaData()

items = sqlalchemy.Table(
    "items",
    metadata,
    sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True),
    sqlalchemy.Column("name", sqlalchemy.String),
    sqlalchemy.Column("description", sqlalchemy.String),
)

engine = sqlalchemy.create_engine(
    DATABASE_URL
)
metadata.create_all(engine)

@app.on_event("startup")
async def startup():
    await database.connect()

@app.on_event("shutdown")
async def shutdown():
    await database.disconnect()
        
    

Step 5: Create API Endpoints for CRUD Operations

Finally, we can create API endpoints for CRUD operations on our items table in the PostgreSQL database. Here’s an example:

        
@app.post("/items/")
async def create_item(item: Item):
    query = items.insert().values(name=item.name, description=item.description)
    last_record_id = await database.execute(query)
    return {**item.dict(), "id": last_record_id}

@app.get("/items/{item_id}/")
async def read_item(item_id: int):
    query = items.select().where(items.c.id == item_id)
    item = await database.fetch_one(query)
    return item

@app.put("/items/{item_id}/")
async def update_item(item_id: int, item: Item):
    query = items.update().where(items.c.id == item_id).values(name=item.name, description=item.description)
    await database.execute(query)
    return {**item.dict(), "id": item_id}

@app.delete("/items/{item_id}/")
async def delete_item(item_id: int):
    query = items.delete().where(items.c.id == item_id)
    await database.execute(query)
    return {"message": "Item deleted successfully"}
        
    

And that’s it! You have now successfully built a PostgreSQL-backed API using FastAPI in just a few minutes. You can test your API using tools like curl, Postman, or any other API testing tool. Happy coding!

0 0 votes
Article Rating

Leave a Reply

3 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@johannesschmidt8611
13 days ago

What tool do you use to generate the voice?

@johannesschmidt8611
13 days ago

Enjoying the content! I have some suggestions, might share them in the repo later

@rangabharath4253
13 days ago

Awesome 🙂

3
0
Would love your thoughts, please comment.x
()
x