A basic introduction into FastAPI

FastAPI Introduction

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

Key Features

  • Fast: Very high performance, on par with NodeJS and Go
  • Fast to code: Increase the speed to develop features
  • Fewer bugs: Reduce developer errors
  • Intuitive: Great editor support and takes less time to debug
  • Robust: Get a production-ready code. With automatic interactive documentation
  • Standards: Compatible with the open standards for APIs
  • Interactive API docs: Provided by Swagger UI and ReDoc

FastAPI stands on the shoulders of giants:

So before we start using it, we need to install it right. So the next step will help you to install the fast API and its required dependencies.

I used Anaconda to install fast API and unicorn, from anaconda prompt

Installation

To use FastAPI we need to install a couple of things

  1. pip install fastapi
  2. pip install uvicorn

So let us try out this fastAPI with a simple program to being

A simple FastAPI file will be

from fastapi import FastAPIapp = FastAPI()@app.get(“/”)async def root():
return {“message”: “Hello World”}

save this file with name main and .py extension and use any python editor.

To run it

  • Create a file main.py with above code
  • Run API with command in anaconda prompt (if you use anaconda to install the fast API and uvicorn)
uvicorn main:app --reload

To check it open the browser

http://127.0.0.1:8000

You will see the JSON response as:

{“message”: “Hello World”}

Interactive API docs

http://127.0.0.1:8000/docs

You will now be able to see the automatic interactive API documentation

Swagger UI

Alternative API docs

http://127.0.0.1:8000/redoc
ReDoc

Code explanation

  1. FastAPI is a Python class that provides all the functionality for your API
  2. app variable will be an “instance” of the class FastAPI, this will be the main point of interaction to create all your API
  3. Path — refers to the last part of the URL starting from the first / and is also commonly called an “endpoint” or a “route”
  4. @app.get(“/”) tells FastAPI that the function right below is in charge of handling requests

Path Parameters

You can declare path “parameters” or “variables” with the same syntax used by Python format strings:

from fastapi import FastAPIapp = FastAPI()@app.get(“/items/{item_id}”)async def read_item(item_id):
return {“item_id”: item_id}

The value of the path parameter item_id will be passed to your function as the argument item_id.

So, if you run this example, you will get output with foo

http://127.0.0.1:8000/items/foo

Path parameters with types

You can declare the type of a path parameter in the function, using standard Python type annotations:

from fastapi import FastAPIapp = FastAPI()@app.get(“/items/{square}”)async def read_item(square: int):
return {“Square of the number”: square*square}

Data validation

Now if you go to the browser at

http://127.0.0.1:8000/items/foo

The same error would appear if you provided a float instead of an int, as in:

http://127.0.0.1:8000/items/4.2

Predefined values

If you have a path operation that receives a path parameter, but you want the possible valid path parameter values to be predefined, you can use a standard Python Enum.

Create an Enum class

Import Enum and create a subclass that inherits from str and from Enum.

By inheriting from str the API docs will be able to know that the values must be of type string and will be able to render correctly.

And create class attributes with fixed values, those fixed values will be the available valid values:

from enum import Enumfrom fastapi import FastAPIclass ModelName(str, Enum):alexnet = “alexnet”
resnet = “resnet”
lenet = “lenet”
app = FastAPI()@app.get(“/model/{model_name}”)async def get_model(model_name: ModelName):if model_name == ModelName.alexnet:
return {“model_name”: model_name, “message”: “Deep Learning FTW!”}
if model_name.value == “lenet”:
return {“model_name”: model_name, “message”: “LeCNN all the images”}
return {“model_name”: model_name, “message”: “Have some residuals”}

Path parameters containing paths

Let’s say you have a path operation with a path /files/{file_path}.

But you need file_path itself to contain a path, like home/johndoe/myfile.txt.

So, the URL for that file would be something like/files/home/johndoe/myfile.txt.

Query Parameters

When you declare other function parameters that are not part of the path parameters, they are automatically interpreted as “query” parameters.

from fastapi import FastAPIapp = FastAPI()fake_items_db = [{“item_name”: “Foo”}, {“item_name”: “Bar”}, {“item_name”: “Baz”}]@app.get(“/items/”)async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]

The query is the set of key-value pairs that go after the ‘?’ in a URL, separated by ‘&’ characters.

For example, in the URL:

http://127.0.0.1:8000/items/?skip=0&limit=10

the query parameters are:

  • skip: with a value of 0
  • limit: with a value of 10

As they are part of the URL, they are “naturally” strings.

But when you declare them with Python types (in the example above, as int), they are converted to that type and validated against it.

As query parameters are not a fixed part of a path, they can be optional and can have default values.

In the example above they have default values of skip=0 and limit=10.

So, going to the URL:

http://127.0.0.1:8000/items/

would be the same as going to:

http://127.0.0.1:8000/items/?skip=0&limit=10

But if you go, for example to:

http://127.0.0.1:8000/items/?skip=20

The parameter values in your function will be:

  • skip=20: because you set it in the URL
  • limit=10: because that was the default value

Conclusion

The aim of the article was to give a basic introduction to Fast API to get started with it. So we have learned the basic features of fast API, installation commands and basic program to understand the working of FastAPI. This post looked into the path parameters and how to declare it with data validation.

For more information fast API please refer to https://fastapi.tiangolo.com/.

Reference

  1. https://fastapi.tiangolo.com/
  2. https://www.python.org/

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store