FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints. It is one of the fastest web frameworks available for building APIs in Python and is gaining popularity for its speed, ease of use, and integration with Python’s type system.
In this tutorial, we will walk you through how to build your first API using FastAPI. We will create a simple API that will allow us to get, create, update, and delete information about users.
Step 1: Install FastAPI
The first step is to install FastAPI and uvicorn, which is the ASGI server that will allow us to run our FastAPI application.
You can install FastAPI and uvicorn using pip:
pip install fastapi
pip install uvicorn
Step 2: Create a FastAPI application
Next, we will create a new Python script and import the necessary modules from FastAPI. Create a new file named main.py and add the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"}
This code creates a new FastAPI application and defines a single route at the root URL ("/") that returns a simple JSON response with the message "Hello World".
Step 3: Run the FastAPI application
Now, we can run our FastAPI application using uvicorn. Open a terminal and run the following command:
uvicorn main:app --reload
This command tells uvicorn to run the app variable from the main.py file, and –reload enables automatic reloading of the server when changes are made to the code.
You should see output indicating that the server is running at http://127.0.0.1:8000/. Open a web browser and navigate to this URL to see the "Hello World" message displayed in JSON format.
Step 4: Create routes for CRUD operations
Now that we have our FastAPI application running, let’s create routes for the CRUD (Create, Read, Update, Delete) operations for users. First, let’s define a data model for our users. Add the following code to main.py:
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
email: str
Next, let’s define routes for getting all users, creating a new user, updating a user, and deleting a user. Add the following code to main.py:
from typing import List
users = []
@app.get("/users", response_model=List[User])
def read_users():
return users
@app.post("/users")
def create_user(user: User):
users.append(user)
return users[-1]
@app.put("/users/{user_id}")
def update_user(user_id: int, user: User):
users[user_id] = user
return user
@app.delete("/users/{user_id}")
def delete_user(user_id: int):
deleted_user = users.pop(user_id)
return deleted_user
Step 5: Test the API endpoints
Now that we have defined our routes for CRUD operations, let’s test them using a tool like Postman or cURL. Start the FastAPI server using the uvicorn command we used earlier and make requests to the following endpoints:
- GET http://127.0.0.1:8000/users : Returns a list of all users
- POST http://127.0.0.1:8000/users : Creates a new user
Body: {"id": 1, "name": "Alice", "email": "alice@example.com"} - PUT http://127.0.0.1:8000/users/0 : Updates the user with ID 0
Body: {"id": 1, "name": "Alice Smith", "email": "alice.smith@example.com"} - DELETE http://127.0.0.1:8000/users/0 : Deletes the user with ID 0
You should see the appropriate responses for each request, confirming that the CRUD operations are working as expected.
Congratulations! You have successfully built your first API using FastAPI. FastAPI’s performance, ease of use, and integration with Python’s type system make it a powerful tool for building APIs in Python. Further explore the documentation and experiment with more advanced features to build even more sophisticated APIs. Happy coding!
Thanks a lot pro for this tutorials 🙂🙂🙂
Great video! Very helpful overview and great explanations of the details. It's the most thorough (and practical) I've come across. Thanks!
Stellar tutorial. For anyone doing this now – pgAdmin doesnt have a Create > Server option, use Register > Server instead 🙂
So much to learn. Thank you for making this video.
Hi Zander. Your Django ecommerce series is great. I think it'll be perfect to recreate your ecommerce series using FastAPI to create APIs instead of Django for APIs. FastAPI is faster and API first package. So, we can enjoy faster API calls for large scale systems. What do you say?
Nice tutorial, Bro!
Thank you! You explain really calm and sequently 🙏
God's and Angel's bless and protect you always.
Best all around tutorial 🤓
Thank very much. What a wonderful video.👍
I had to change the first line in the 'Dockerfile' to: FROM python:3.9
…because it was trying to use Python 3.11 and caused a build break with 'greenlet' and the failure when the c_app tries to use 'psycopg2'. Hope this helps in case someone else has the same issue I had. It all worked after citing to use *Python 3.9*.
first of all thanks for this video and please tell me this theme name
thanks god, not an indian tutorial!
This was very helpful, great stuff
Xander My Man Please Start a Course about Creating telegram Robots
For you M1 mac users that get a problem when trying to migrate your db with the "docker-compose run app alembic revision –autogenerate -m "New Migration", you can try what i found to work.
The error text: sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) SCRAM authentication requires libpq version 10 or above
So to fix that open the Dockerfile and change python version to 3.11 = FROM python:3.11
Then after RUN pip3 install –upgrade pip ..You add the following 2 lines:
RUN apt update -y && apt install -y build-essential libpq-dev
RUN pip3 install psycopg2-binary –no-binary psycopg2-binary
Hope this help!
Got an error related to greenlet on docker-compose build.
Fixed by changing greenlet version to 2.0.a2 on requirements.txt. Not sure it broke something but the docker-compose build command worked.
As a backend engineer, docker is most important and confusing for beginners. You made it look really easy!! Thank you!
Ha Ha!!! I had forgotten the env vars for pgadmin… I was going along and ran the 'up' command and it threw an error. Took me a hot second to realize I never added the environment variables for it. Funny enough… I had paused the video to troubleshoot it and work through everything, then sure enough… you hit the same error code. Kind of put a smile on my face.
Love the content!
I need update and delete methods for this? Can someone help me with this