Create an App using Postgres, SQL Alchemy, Async, and more with this Fast API Crash Course Code-along

Posted by


In this tutorial, we will be building a FastAPI app that interacts with a Postgres database using SQL Alchemy. We will be using asynchronous programming to make our app more performant and scalable. We will also be covering various other tools and libraries that are commonly used in building FastAPI apps.

Let’s get started!

Step 1: Install necessary dependencies

First, we need to install the necessary dependencies for our project. We will be using FastAPI, SQL Alchemy, Uvicorn, and other libraries. You can install them using pip:

pip install fastapi uvicorn asyncpg sqlalchemy databases

Step 2: Set up the database

Next, we need to set up our Postgres database. You can create a new database in Postgres using a tool like pgAdmin or by running the following command in your terminal:

createdb myapp

Step 3: Create the FastAPI app

Now, let’s create our FastAPI app. Create a new file called main.py and add the following code:

from fastapi import FastAPI, HTTPException
from sqlalchemy import create_engine, Column, Integer, String, MetaData, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

DATABASE_URL = "postgresql://localhost/myapp"

engine = create_engine(DATABASE_URL)

Base = declarative_base()

metadata = MetaData()

users = Table(
    "users",
    metadata,
    Column("id", Integer, primary_key=True, index=True),
    Column("name", String),
    Column("email", String),
)

Session = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Step 4: Create the models

Next, let’s create the models for our app. Add the following code to main.py:

class User(Base):
    __table__ = users

Step 5: Create the API routes

Now, let’s create the API routes for our app. Add the following code to main.py:

app = FastAPI()

@app.get("/users/{user_id}")
async def get_user(user_id: int):
    async with Session() as session:
        user = await session.execute(users.select().where(users.c.id == user_id))
        user = user.fetchone()
        if user is None:
            raise HTTPException(status_code=404, detail="User not found")
        return user

@app.post("/users")
async def create_user(name: str, email: str):
    async with Session() as session:
        new_user = User(name=name, email=email)
        session.add(new_user)
        await session.commit()
        return new_user

Step 6: Run the app

Finally, we can run our FastAPI app using Uvicorn. Run the following command in your terminal:

uvicorn main:app --reload

You should see output indicating that the server is running. You can now navigate to http://localhost:8000/docs in your browser to see the Swagger documentation for your API.

That’s it! You have successfully built a FastAPI app that interacts with a Postgres database using SQL Alchemy. You have also learned how to use asynchronous programming to make your app more performant and scalable.

I hope you found this tutorial helpful. Happy coding!

0 0 votes
Article Rating
21 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@andrirahmadani1332
2 months ago

Thank u so much

@Aniket_0314
2 months ago

I'm just getting started with fast api . I'm very excited to learn from this. Would leave a comment once i end up completing it

@hasnainhasib4548
2 months ago

For someone new to FastAPI, this tutorial is invaluable. While other creators doing marathon you took your time, very easy to catch up .Thank you so much for your thorough explanation.

@Lotrick
2 months ago

1:35:24
students have role set to 2 in the json file, but

1:37:23
they all have role set to NULL in the db

why?

@teus8964
2 months ago

would be nice if u update the tutorial with the addition of dockerCompose for the services

@FranciscoAgamez
2 months ago

The writer of fast API is from Colombia, South America! 🙂

@history2pie
2 months ago

we're so lucky to have you

@victorychang1294
2 months ago

Thank you for such a detailed and informative course

@shounakdey126
2 months ago

Nice course for beginners.
It would be great if you could share how the update will work on the course model?

@serujo123
2 months ago

Hi, i am watching this video, but how query views in postgre (not table). i get error for this. pls

@user-ju5zm4vw1n
2 months ago

Very informative 👍

@user-hy4sz8lx5z
2 months ago

I thought this was going to be a 3hrs fast api crash course but it ended up being a 2 days solving fast api crashes course

@dukeHH26
2 months ago

Very well explained and even complete to go on on ones own. I read and watched a lot on the topic on utube, udemy and what not… These 3 hours were very worthwhile investing. thanks so much.

@godzilla870
2 months ago

This is great! I love your work. For me its perfect! Fast API + VUE Really great resource, Thanks<3

@StepsToEffectiveParentin-iz9xd
2 months ago

Now you are my crash=) not your crash course

@dinugherman8785
2 months ago

Congrats for a great tutorial! I understand that Swagger/OpenAPI is very helpful in such contexts, and then I feel that for real-world projects an emphasis on a proper test suite, most likely using pytest, is actually more beneficial, and should have a higher priority over the OpenAPI UI.

@leo3030100
2 months ago

Thank you for the lesson! Your teaching method is excellent, congratulations on the content.

@mdaslamknl
2 months ago

Good

@laalbujhakkar
2 months ago

00:27:00 in Python 3.10 I had to declare bio: Optional[str]=None or it wasn't having any of it.

@kartikramesh8695
2 months ago

Thank you for the tutorial, it was very helpful. I was wondering is there a way to find out why the seed data is not migrated to my database. I see python code is reading the json file but it’s not inserting the seed data.