Author avatar

Gaurav Singhal

Explore Python Libraries: FastAPI

Gaurav Singhal

  • Jun 29, 2020
  • 8 Min read
  • 235 Views
  • Jun 29, 2020
  • 8 Min read
  • 235 Views
Data
Data Analytics
Machine Learning

Introduction

FastAPI is a modern Python web framework which with a number of advantages, including:

  • It is one of the fastest (high-performance) web frameworks available.
  • It takes advantage of type annotation support of Python 3.6+ for better data validation and editor support.
  • It utilizes Python's Async power, which is useful for building asynchronous APIs.
  • It generates standards based on open standards such as OpenAPI and JSON Schema.
  • It is robust and easy to use and learn.

So in this guide, you will be exploring one of the newest and finest Python web framework libraries.

Getting Started

There are just three basic steps to install, create, and run FastAPI.

Installation

1
pip install fastapi
shell

You will also need an ASGI (Asynchronous Server Gateway Interface) server such as Uvicorn.

1
pip install uvicorn
shell

Create your App

To see what the simplest FastAPI app could look like, create a new Python file called main.py

1
2
3
4
5
6
7
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"hello": "world"}
python

Run your App

To run the app, just execute like this :

1
uvicorn main:app --reload
shell

After running the above command, the server starts as follows:

1
2
3
4
5
6
7
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL
+C to quit)
INFO:     Started reloader process [4136] using
statreload
INFO:     Started server process [12988]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
shell

Diving Deeper

Path Parameters

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
2
3
@app.get("/course/{course_id}")
def my_course(course_id: int):
    return {"course_id": course_id}
python

If you provide the URL incorrectly, say for course/100s, you will get the following validation error.

1
2
3
4
5
6
7
8
9
10
11
12
{
    "detail": [
        {
            "loc": [
                "path",
                "course_id"
            ],
            "msg": "value is not a valid integer",
            "type": "type_error.integer"
        }
    ]
}
json

And if you run the example for a URL such as course/100, the call will get this response:

1
{"course_id":100}
json

Query Parameters

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.

1
2
3
4
5
dummy_data = [i for i in range(100)]

@app.get("/my/page/items/")
async def read_item(page: int = 0, limit: int = 0, skip: int = 1):
    return dummy_data[page*10: page*10 + limit: skip]
python

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:

  • page(int): 2
  • limit(int): 29
  • skip(int): 2

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]

Request Body

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:

1
2
3
4
5
6
7
8
9
10
11
from pydantic import BaseModel

class MyItem(BaseModel):
    name: str
    info: str = None
    price: float
    qty: int

@app.post("/purchase/item/")
async def create_item(item: MyItem):
    return {"amount": item.qty*100, "success": True}
python

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.

1
curl -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}"
shell

It will give the response:

1
{"amount":200,"success":true}
json

Form Data

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.

1
pip install python-multipart
shell

For this demo, I have created a login view, that takes username and password as form fields.

1
2
3
4
5
from fastapi import Form

@app.post("/accounts/login/")
async def login_view(username: str = Form(...), password: str = Form(...)):
    return {"success": True}
python

Automatic Docs

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.

Swagger UI

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 .

ReDoc

Alternatively, you can use redoc for your API documentation.

Check out more about here .

Exploring Features

Performance

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.

Development Speed

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

Security and authentication are automatically integrated. All the security schemas defined by OpenAPI and Starlette are included.

Starlette Features

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:

  • Websocket support
  • GraphQL support
  • GZip, Static Files, Streaming responses
  • Session and Cookie support

Check out https://fastapi.tiangolo.com/features/ to explore more fastAPI features.

Conclusion

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.

4