FastAPI: The Modern Age API Framework For Pythonista

Build And Host A Production-Ready API In Python

Shritam Kumar Mund
Analytics Vidhya

--

The Flash by DCcomic

Web APIs have become increasingly important to the operation of modern businesses. As companies become more reliant on data, the importance of data communications continues to grow. While data technologies are emerging frequently, we need a fast, high-performance, and robust framework to build our APIs.

Why FastAPI?

https://fastapi.tiangolo.com/

FastAPI, a modern, fast (high-performance), a web framework for building APIs with Python 3.6+. Its performance can be compared with NodeJS and Go and it is rated as one of the fastest Python frameworks available. Tech giants like Microsoft, Netflix, Uber amongst many other corporations are already started building their APIs with the FastAPI library. The framework is designed to optimize the experience so that we can write simple code to build production-ready APIs with best practices by default. Without further ado, let’s learn how can we build a robust API solution using FastAPI.

Article Summary

  1. Problem Statement
  2. Installation and Setup
  3. “Hello World” to FastAPI
  4. Integrate the Database
  5. Build the real-world API
  6. FastAPI Swagger UI
  7. Host it on cloud
  8. Conclusion

Problem Statement

Today we are going to build and deploy an API for the Retail Industry, having the data of retail products. The API will have the ability to,

  1. Add data to a database
  2. Update the existing data (This’ll include marking the data as updated and the time when the data is getting updated)
  3. Delete data from the database
  4. View the data by calling the unique id

The database we're going to use today is MongoDB. And we’ll explore the MongoDB Atlas to connect the database to our API.

Installation and Setup

It’s always good to start by creating a virtual environment. Create the virtual environment and install FastAPI using pip3.

$ pip3 install fastapi

We will also need an ASGI server for production, such as Uvicorn.

$ pip3 install uvicorn

Later, we need a MongoDB driver to connect our API with the database. For this, we’ll go with Motor driver. Motor presents a coroutine-based API for MongoDB which supports asyncio.

$ pip install motor

We need a DNS toolkit for Python which can support almost all record types.

$ pip install dnspython

These are all the dependencies that we need to create a full-fledge high-performance API using python3.

Hello World to FastAPI

To get started, we’ll create a “hello world” app using FastAPI and run it using uvicorn server. This will give you a very quick overview of how everything works.

Create a file app.py with:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
return {"message": "Hello World"}

Run the server with:

$ uvicorn app:app -- reload

Open your browser at http://127.0.0.1:8000/

You will see the JSON response as: {"message": "Hello World"}

The JSON response is the same dictionary that you returned from the function in your FastAPI application.

You can also view the interactive API documentation at http://localhost:8000/docs:

http://localhost:8000/docs

Integrate the app to the Database

As it has been clear so far, we are using MongoDB as our database, let me tell you we are going to use the most advanced cloud database service on the market, MongoDB Atlas.

  1. Let’s create a cluster in MongoDB Atlas with the default 512MB configuration. And name it “FasterAPI”.

2. To connect the database to our app, we’ll take the help of MongoDB Compass. Let’s connect it using the configuration that has been set during the creation of the cluster.

3. Connect with MongoDB compass.

Build the Realworld API

To build a real-world Retail API, we will use some basic HTTP functionalities which are known as CRUD operations. CRUD stands for Create, Read, Update, and Delete, which are four primitive database operations.

Using FastAPI we can Create, Read, Update, and Delete data in our database using 4 predefined methods.

  • @app.get()
  • @app.post()
  • @app.put()
  • @app.delete()

This HTTP functionality should execute below the app instance, which is an instance of the class FastAPI. This will be the main point of interaction to create our API.

app = FastAPI()

And this is the same app, which initiates the API while we run using uvicorn app:app --reload

It’s always a good practice to defined a Pydantic Schema that represents how the data should be stored in the Database. In Pydantic, let’s define a schema to store our data to MongoDB.

In the code above, we defined a Pydantic Schema called Items , which defines all the fields with respect to their type. The schema_helper function will help the CRUD operation data to be mapped as a dictionary with the Retail parameters i.e SKU, Brand Name, Title, Thumbnail, Available Price, and MRP.

Yey! The script below is all we need to build our API, where we have defined CRUD functionality along with the schema.

FastAPI Swagger UI

FastAPI provides web user interfaces. As the framework is based on OpenAPI, there are multiple options to be explored yet, but let’s look into the most common and important features of this framework.

Switch to http://localhost:8000/docs to interact with FastAPI swagger.

POST Method:

We’ll create a data to out collection using the POST method,

{“sku”: “NI114D0EY-Q11”,
“brand_name”: “Nike Sportswear”,
“title”: “AIR MAX 2090 UNISEX — Trainers — black/wolf grey/black/anthracite”},
“thumbnail”: “https://img01.ztat.net/article/spp-media-p1/9866ece8595630bfbc16501686540429/9c6d5c0c4ab14091b9714501865dcd66.jpg",
“available_price”: “£55.99”,
“mrp”: “£59.99”
}

GET Method:

Get the updated data by giving id as the input.

PUT Method:

Update the data. Here if we update the data using the Post method, 2 fields will be added to the data fields,

1. “update”: True2. “updated_time”: <Time when the data was updated>

DELETE Method:

Delete the record from the collection using the Id field.

Host the API on the cloud:

Lastly, let’s deploy our API into Heroku.

Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud.

To deploy it on the production environment, collect all your requirements into a requirements.txt file.

$ pip freeze > requirements.txt

Please make sure uvloop and httptools are part of your requirements file.

API Url: https://retail-fastapi.herokuapp.com/

That’s great!

Feel free to fork and play with the code I used to create this API in this repository.

Conclusion:

Congratulations, your first production-ready API with FastAPI is live. I hope it was easy and helpful. Feel free to take this FastAPI article as a reference and try it out and build some amazing web APIs.

I hope this article will create a motivation for you to build and host your APIs into your production.

I will see you on another cool topic next time. Till then,

Stay Safe..! Keep Learning..!

Thank you for reading!

Follow me on Medium for the latest updates. 😃

--

--

Shritam Kumar Mund
Analytics Vidhya

Data Engineer | Python Programmer | Instructor | Tech Enthusiast - https://shritam.net/