Developing a REST API using FastAPI, Async SQLModel, and PostgreSQL

Posted by

Building a REST API with FastAPI, Async SQLModel, and PostgreSQL

Building a REST API with FastAPI, Async SQLModel, and PostgreSQL

FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.7+ based on standard Python type hints.

Async SQLModel is an asynchronous ORM (Object Relational Mapper) built on top of SQLAlchemy and Pydantic that allows you to interact with your database using Python types. PostgreSQL is a popular open-source relational database management system that is known for its reliability and performance.

In this article, we will walk through the process of building a REST API using FastAPI, Async SQLModel, and PostgreSQL.

Step 1: Setting up the environment

First, you will need to install FastAPI, Async SQLModel, and the asyncpg driver for PostgreSQL. You can do this using pip:

pip install fastapi[all] sqlalchemy databases asyncpg

Step 2: Creating the database model

Next, you will define your database model using SQLModel. Here is an example of a simple User model:

    
    from sqlmodel import SQLModel, Field

    class User(SQLModel, table=True):
        id: int = Field(primary_key=True)
        name: str
        email: str
    
    

Step 3: Creating the API with FastAPI

Now, you will create your API using FastAPI. Here is an example of a simple API endpoint for creating a new user:

    
    from fastapi import FastAPI
    from asyncorm import Database
    from models import User

    app = FastAPI()

    @app.post("/users/")
    async def create_user(user: User):
        db = Database("postgresql://user:password@localhost/dbname")
        await db.connect()
        await db.insert(user)
        await db.disconnect()
        return {"message": "User created successfully"}
    
    

Step 4: Running the API

Finally, you can run your API using the uvicorn server. Run the following command in your terminal:

uvicorn your_api_file:app --reload

Your API should now be up and running! You can test it using a tool like Postman or cURL.

Conclusion

Building a REST API with FastAPI, Async SQLModel, and PostgreSQL is a powerful and efficient way to create APIs with Python. By following the steps outlined in this article, you can quickly build a robust API that interacts with a PostgreSQL database asynchronously.

0 0 votes
Article Rating
13 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@SsaliJonathan
5 months ago

Hi guys,
Kindly click the like button because this video was hard to make.
Please join me on my discord server here. https://discord.gg/jqde9VSG

@andriykostenko3688
5 months ago

Nice job !!!

@densondube369
5 months ago

Hey Jonathan, I have config.py just as you have it on your video, but settings = Setting() has Settings() underlined( error = Argument missing for parameter "DATABASE_URL"). Why?

@martinmiz
5 months ago

Another great tutorial. Thank you very much. I would like to request for a tutorial of FastAPI with React, showing the frontend and backend usage of the API. I would also like to see how you handle storage of other data files like images in the API database.

@andersonlontsi299
5 months ago

Thank you sir. I followed your DRF tutorial and even deployed my app , but Please i have a serious issue managing migrations production. i made some research and decided not to push my migration files anymore so that the command:"release: python manage.py migrate –no-input" in the procfile will take care of migrating everything.

But i don't understand why added a field and migrations occured locally and are working fine but in production there is this error:"column main_item.price does not exist". Please sir could you make a video to explain us the best practices for handling migrations/database changes in production? I'm sure it will help more than one. i reall will be grateful 🙏🙏

It is a backend on which i'll certainly have to be doing changes from time to time and i don't want this to happen when there will be actual data in the backend( will soon release the app i'm working on). Since so far i have been resolving this problem by formating the database😔😥 It really hurts

@deevirus6725
5 months ago

How to read Excel file form storege and upload it on firestore plz make ASAP 😅

@arminkessler2566
5 months ago

Hi Jonathan, could you include Authentication in a next part of this serie of videos. Thanks in advance.

@macmillerlover
5 months ago

hello jo, i wanted to make a request. could you please make a full course on testing with python? especially mocking

@derekstevens164
5 months ago

My wife's son is gay

@netkap9920
5 months ago

awsome

@coff3andprograming
5 months ago

I love FastAPI❤

@illuminaughty666
5 months ago

TBH this channel got me so much interest and motivation to learn FastAPI

@SsaliJonathan
5 months ago

Hey, the comment section is really quiet.