DEV Community

Cover image for Getting Started with FastAPI
Max Ong Zong Bao
Max Ong Zong Bao

Posted on • Originally published at maxongzb.com

Getting Started with FastAPI

The original post was on Getting Started with FastAPI - Reading Time: 5 Mins and cover image by chuttersnap on Unsplash

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 
Enter fullscreen mode Exit fullscreen mode

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}

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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.

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.

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

Discussion (0)