FastAPI is a modern web framework for building APIs with Python 3.6+ which is based on standard Python type hints. It is fast (high-performance), web-based (based on standard Python types and function-based views), and also introduces automatic Interactive API documentation. In this tutorial, we will go through how to use FastAPI to build APIs in Python.
Prerequisites:
Make sure you have Python 3.6 or higher installed on your system. You can check this by running python --version
in your command line or terminal.
Step 1: Installing FastAPI
You can install FastAPI using pip, which is a Python package manager. Run the following command in your terminal to install FastAPI and uvicorn (a lightning-fast ASGI server):
pip install fastapi uvicorn
Step 2: Creating a FastAPI App
To create a FastAPI app, you need to create a Python file and import FastAPI from the fastapi package. Then, create an instance of the FastAPI class. Here’s an example of a simple FastAPI app:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, World"}
Save this code to a file named app.py
.
Step 3: Running the FastAPI App
To run the FastAPI app, you need to use uvicorn. Run the following command in your terminal:
uvicorn app:app --reload
This command runs the uvicorn server with the app
module (Python file) and reloads the server whenever you make changes to the code.
Step 4: Accessing the API Documentation
FastAPI automatically generates interactive API documentation for your app, which you can access in your browser. Open your browser and go to http://localhost:8000/docs
to view the API documentation.
Step 5: Adding API Endpoints
You can add more endpoints to your FastAPI app by defining more functions with the @app.get
, @app.post
, @app.put
, @app.delete
, etc., decorators. Here’s an example of adding a POST
endpoint to the FastAPI app:
@app.post("/items/")
def create_item(item: dict):
return item
This endpoint allows you to send a POST request with a JSON payload containing an item, which is then returned as the response.
Step 6: Handling Path Parameters
You can also define path parameters in your FastAPI app by adding them to the endpoint URLs. Here’s an example of an endpoint that takes a path parameter:
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
This endpoint takes an item_id
as a path parameter and returns a dictionary with the item_id
.
Step 7: Handling Query Parameters
You can handle query parameters in your FastAPI app by adding them as function parameters with default values. Here’s an example of an endpoint that takes query parameters:
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
This endpoint takes skip
and limit
query parameters with default values and returns a dictionary with these values.
Step 8: Handling Request Body
You can handle request body data in your FastAPI app by creating a Pydantic model and using it as the parameter type. Here’s an example of an endpoint that takes a request body:
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
@app.post("/items/")
def create_item(item: Item):
return item
This endpoint takes a JSON request body with a name
and price
field, validates the input against the Item
model, and returns the input data.
Conclusion
In this tutorial, we have covered the basics of building APIs with FastAPI in Python. You now know how to install FastAPI, create a FastAPI app, run the app with uvicorn, access the interactive API documentation, add API endpoints, handle path and query parameters, and handle request body data. FastAPI is a powerful and easy-to-use framework for building high-performance APIs in Python.
💡 Get my FREE 7-step guide to help you consistently design great software: https://arjancodes.com/designguide.
Might mention prerequisites for fastapi install!
How to use fastapi
Proceeds to skip the entire sqlalchemy portion to make it sound easy….
Django has sqlite out of the box…changing from that to something like postgresql or mysql is much better than from dictionaries…
This is really similar to Flask
"fast" repetition joke was great😂
Trying to run the api and consume with a mock client process. Problem is I'm using docker containers and can't access the api from my client procces. How do you run both at the same time?
It's really not clear what the use case for this is. It's not really anything to do with "API". It's a database interface. Just not clear at all what this is for.
silly question, but in the final product where is fastAPI/Python sitting – in your office or on the server? eg perl is on server
really nice
BEST TEACHER EVER LIVED !
I have a question about the code in 10:03, you defined the Selection type is a dictionary but why you can return the selection value in the response object with a list 😀
Thank's From France very nice share
Do you make these codes available anywhere?
how does {item_id=} return item_id=int?? not super familiar with python.
This was great, thank you!
Hi,
I have been using javascript for frontend and have a bit of practice of abckend with js. However, i have been thinking of moving to Python for fastapi and use it as my backend solution for any software that i create. I dont have much expreicne in Python.
Whay would you suggest? Should i solidify my backend skills in js or move to Python and fast api and use it.
I want to have a pleasant experience when bulidng backend and that is very good in security.
Your response would be helpful.
Socketify smokes fastapi
Another thanks for such quality content, that's really cool. Keep going, please.
Hi may I ask you why in category visual studio show error? Thank you
yes: fastapi, then pydantic and starlette and uvicorn and sqlalchemy and then vue.js for the admin and then the api for the communications between all the js and the api backend, then all the crud for all the objects.
Or use Django and focus on the actual problem you want to solve.