FastAPI is a modern Python web framework which with a number of advantages, including:
So in this guide, you will be exploring one of the newest and finest Python web framework libraries.
There are just three basic steps to install, create, and run FastAPI.
1pip install fastapi
You will also need an ASGI (Asynchronous Server Gateway Interface) server such as Uvicorn.
1pip install uvicorn
To see what the simplest FastAPI app could look like, create a new Python file called main.py
1from fastapi import FastAPI
2
3app = FastAPI()
4
5@app.get("/")
6def read_root():
7 return {"hello": "world"}
To run the app, just execute like this :
1uvicorn main:app --reload
After running the above command, the server starts as follows:
1INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL
2+C to quit)
3INFO: Started reloader process [4136] using
4statreload
5INFO: Started server process [12988]
6INFO: Waiting for application startup.
7INFO: Application startup complete.
You can declare parameters to the API call as variables as a function parameter. Here , I have used course_id
as the parameter. Note that the type of the parameter is int
.
1@app.get("/course/{course_id}")
2def my_course(course_id: int):
3 return {"course_id": course_id}
If you provide the URL incorrectly, say for course/100s
, you will get the following validation error.
1{
2 "detail": [
3 {
4 "loc": [
5 "path",
6 "course_id"
7 ],
8 "msg": "value is not a valid integer",
9 "type": "type_error.integer"
10 }
11 ]
12}
And if you run the example for a URL such as course/100
, the call will get this response:
1{"course_id":100}
The other way of providing parameters to API calls is by providing them as query parameters. For example: /my/page/items/?page=1&limit=10&order=0
.
Here's how you can implement the function in FastAPI.
1dummy_data = [i for i in range(100)]
2
3@app.get("/my/page/items/")
4async def read_item(page: int = 0, limit: int = 0, skip: int = 1):
5 return dummy_data[page*10: page*10 + limit: skip]
In the above example, there are three parameters set. So for a URL such as http://127.0.0.1:8000/my/page/items/?page=2&limit=29&skip=2
, the parameters will be:
So the response of the above URL will be:
1[20,22,24,26,28,30,32,34,36,38,40,42,44,46,48]
When you need to send data from the client to the server, you can use the request body.
Note: To send data using the request body, use the POST
method. You cannot use the GET
method in the request body.
To declare a request body, use Pydantic models and declare the request body as:
1from pydantic import BaseModel
2
3class MyItem(BaseModel):
4 name: str
5 info: str = None
6 price: float
7 qty: int
8
9@app.post("/purchase/item/")
10async def create_item(item: MyItem):
11 return {"amount": item.qty*100, "success": True}
In the above example, I have created a model named MyItem
which has certain attributes. Now when there is a POST
request on endpoint /purchase/item/
, it will capture the attribute values and return with success.
Let's test this API call using CURL
.
1curl -X POST "http://127.0.0.1:8000/purchase/item/" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"name\":\"sample item\",\"info\":\"This is info for the item\",\"price\":40,\"qty\":2}"
It will give the response:
1{"amount":200,"success":true}
In many scenarios, you may need to receive form fields instead of JSON. In such cases, Form
comes to the rescue. The way that HTML forms (<form></form>
) sends data is different from JSON, but FastAPI ensures correct parsing of the data.
To use form data, first install the additional library python-multipart
.
1pip install python-multipart
For this demo, I have created a login view, that takes username
and password
as form fields.
1from fastapi import Form
2
3@app.post("/accounts/login/")
4async def login_view(username: str = Form(...), password: str = Form(...)):
5 return {"success": True}
FastAPI comes with a battery included for automated API documentation in a nice and beautiful web user interface. Two default automatic docs come with fastAPI.
This is an interactive exploration of your API calls. Here, you can view and test your API calls in a nice, user-friendly interface. Read more here .
Alternatively, you can use redoc for your API documentation.
Check out more about here .
FastAPI apps running under Uvicorn use one of the fastest Python web frameworks, second only to Starlette and Uvicorn itself (used internally by FastAPI). Check out the benchmarks.
Creating REST API's endpoints with FastAPI takes less than five minutes. It increases the speed of developing features by about 200% to 300%. It's easy to use and learn and requires less time reading docs.
Security and authentication are automatically integrated. All the security schemas defined by OpenAPI and Starlette are included.
FastAPI is a subclass of Startlette, so almost all of the functionality you have in Starlette works in the same way. Some of the main features include:
Check out https://fastapi.tiangolo.com/features/ to explore more fastAPI features.
FastAPI is an emerging and relatively new web framework. If you are looking for a fast, light-weight, high-performance web API framework for machine learning, deep learning, or any other project that requires a web application, then FastAPI is the right choice.
In this guide, you explored the FastAPI library, an emerging web framework in Python. Thanks for reading. If you have any questions, feel free to contact me at CodeAlphabet.