Getting Started with FastAPI - Reading Time: 5 Mins

Introduction

undraw dev productivity umsq

Building API is a tough job. You are the data plumber to create APIs. If you think GraphQL addresses this problem. I will burst your bubble and say you are sorely wrong. I believe it is just another compliment to RESTful API that is lacking in the technical department. This is from my experience & understanding of building APIs in both Flask & Django.

While using Postman to mock and OpenAPI to formalise the API documentation as a contract. You will be surprised by the amount of work needed to build an API. You can look at this API lifecycle that is provided by API Evangelist to give you a good overview of why I think that way.

Why FastAPI?

undraw code thinking 1jeh

The reason why I would choose FastAPi to create API. Besides being Fast which is a given for it. FastAPI generates OpenAPI Specification documentations directly without you spending the effort to install an additional library to generate the OpenAPI documentation for Flask or Django.

Despite sharing some DNA to Flask than Django. I found that it was faster and easier to build APIs with it. I do not need to go through tons of setup and configuration to make it work. It really shares some voodoo magic in the out of the box experience from Django.

Getting Started With FastAPI

undraw developer activity bv83

In this section, you will learn how to create an API using FastAPI. I will be using the typer portion of the FastAPI documentation.

Installation

The create python project called example_fastapi and a virtual environment fast_api.

Now let us go to your terminal and install the following libraries within the fast_api virtual environment:

pip install fastapi # The FastApi library
pip install uvicorn # The ASGI server for serving asynchronous http requests 

Creating the API using FastAPI

Once you had installed these libraries. We shall now create a new python file called main.py:

from typing import Optional  # Optional allows the variable to contain "none" as a value but you can set the data type
from fastapi import FastAPI  # Calling the FastAPI library

app = FastAPI()  # Declaring as the main app to use FastAPI

@app.get("/")  # Create GET method API at the Root URL when you go the localhost
def read_root():
    return {"Hello": "World"}

@app.get("/items/{item_id}")  # Create GET method API and goes to the "items" path base upon the "item_id" provided
def read_item(item_id: int, query: Optional[str] = None):  # "item_id" is set as integer & add the parameter "query"
    # Returns the "item_id" that is entered and value of under the parameter called "query"
    return {"item_id": item_id, "query": query}

Running the Server

Alright, now that you had created the API. Let us run the server to serve the API in the command line:

Command line explained

  • uvicorn - The ASGI server to run FastAPI.
  • main - Refers to the main.py
  • app - The object that was declared in main.py under the code app = FastAPI().
  • --reload - It allows auto-reload in whenever a change in the code is detected.
 uvicorn main:app --reload

With the command above executed in the command line. It should display this when your uvicorn is running:

INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     Started reloader process [167091] using statreload
INFO:     Started server process [167093]
INFO:     Waiting for application startup.
INFO:     Application startup complete.

Let us access the endpoint under http://127.0.0.1:8000/items/5?query=somequery url in your browser. Did it show something like this?

API screenshot of browser

Awesome work!!! You had now learnt to create two API endpoints in FastAPI.

FastAPI's Voodoo Begins

undraw mello otq1

Now grasshopper, I know that might be overjoyed in creating your first API in FastAPI. Let me show the voodoo the FastAPI has installed for us right out of the box. By opening another tab in your browser and enter the following url http://127.0.0.1:8000/docs.

It should show this and do play around with the OpenAPI API documentation as you can execute API using it.

openapi docs

Amazing am I right? This was what blew me away when I was reading about it as it's the other way round that the API specification files have to be created when you build an API.

Now, this approach speeds up your process greatly. By skipping it for you to focus on building the API while pacifying your front-end need for API documentation of your API.

When & Where Should You Use FastAPI?

undraw contract uy56

Now that you are armed with basic knowledge on how to create an API in FastAPI. Would you stick with Flask as your first choice when you need an API to be built quick? Before you make the decision, hold your horses, my man. For pure API development without any dependency, my goto choice will be FastAPI as it comes with tons of goodies.

For example, it contains the usual things you might need. Like establishing database connection to store or update a database. Using various types of authentication to authenticate your API. Along with built-in testing to create basic tests and Async tests that is similar to what you get from Django.

For any other purposes, I believe your mileage will vary. As it might not truly replace Flask or Django for now in a web development sense. As a full-fledged alternative for a backend web framework that serves webpages to your client. I had not heard the news about it being used on a massive scale of users. Which that was the case for both Django & Flask. Only time would tell in a few years.

Therefore I would suggest you pick up on either Flask or Django as your bread and butter skillset. Unless you are doing Data Science work. Which does not require you to serve a webpage then, by all means, do it to get things done. But you need to beware of the security and how to lock it down as well. Which Django shines in that aspect as part of their out of the box experience.

Conclusion

undraw High five u364

So I had covered the reasons on why you should learn to use FastAPI because of it's the ease and lack of setup with configuration to create an API with it. You had learnt on how to get started on creating an API using FastAPI with OpenAPI specification documentation generated for you.

After learning all of those, you understand when or where you should use OpenAPI. Which should be a compliment to your existing skillset for Django or Flask. Unless you are doing data science-related work. Which does not require you to serve a webpage to your users.

Lastly, are you looking to specialise yourself as a developer? If it's a Yes. I'm giving away my free ebook called "Picking Your Specialisation as a Developer" for anyone interested to command a higher salary or do the work that you like.

Reference