Getting Started with FastAPI
Tags: webdev, python, startup, datascience
Published: 2020-09-06 04:41:27

The original post was on [Getting Started with FastAPI - Reading Time: 5 Mins](https://www.maxongzb.com/getting-start-with-fastapi-reading-time-5-mins/) and cover image by [chuttersnap on Unsplash](https://unsplash.com/photos/X8ml8C4KTrg)

# Introduction
![undraw dev productivity umsq][1]

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][2] to mock and [OpenAPI][3] 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][4] that is provided by [API Evangelist][5] to give you a good overview of why I think that way.

# Why FastAPI?
![undraw code thinking 1jeh][6]

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][7]

In this section, you will learn how to create an API using FastAPI. I will be using the [typer][8]  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:

```bash
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`:

```python
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. 

```bash
 uvicorn main:app --reload
```

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

```bash
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][9]

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

## FastAPI's Voodoo Begins
![undraw mello otq1][10]

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][11]

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][17]

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"](https://maxongzb.activehosted.com/f/5) for anyone interested to command a higher salary or do the work that you like.

# Reference
* [Postman][2] 
* [OpenAPI][3]
* [API lifecycle][4]
* [API Evangelist][5]
* [FastAPI][19]
* [Why We Switched From Flask To FastAPI ][20]
* [Introducing FastAPI][21]
* [30 Days of Python - Day 14 - Web App with Flask, FastAPI, ngrok, and Invictify][22]
* [Build Secure Twilio Webhook with Python and FastAPI][23]
* [Typer the FastAPI of CLIs][8]
* [The Benefits Of OpenAPI Driven API Development][24]
* [SQL Connection FastAPI][13]
* [Security & Authentication][14]
* [Testing][15]
* [Async Tests][16]
* [Undraw][25]


[1]: //images.ctfassets.net/ly2f59p4unnn/6gNcHp9BcShHkKW3nfOBMg/a9ef11621dd65d94319e30cd10148f48/undraw_dev_productivity_umsq.png
[2]: https://www.postman.com/
[3]: https://swagger.io/specification/
[4]: https://apievangelist.com/2020/01/02/what-is-the-api-life-cycle/
[5]: https://apievangelist.com/
[6]: //images.ctfassets.net/ly2f59p4unnn/69OFeWWLAuYVYzUFYKDvn8/205cc5f63348a89e2ac7e74d9c3b27c9/undraw_code_thinking_1jeh.png
[7]: //images.ctfassets.net/ly2f59p4unnn/3m9OJOkkn9gNJu97BF5Yb/ca22b5fab109c9e6a4d5b111185a2bba/undraw_developer_activity_bv83.png
[8]: https://fastapi.tiangolo.com/#typer-the-fastapi-of-clis
[9]: //images.ctfassets.net/ly2f59p4unnn/3NOsCIInqbvyFpEkUCEzIM/3af33cd43c79fe64cbccf13aba6ab57e/API_screenshot_of_browser.png
[10]: //images.ctfassets.net/ly2f59p4unnn/3dV9leWWQia80Cw31WSlLm/18430b49cb28634b8db664101e19cd61/undraw_mello_otq1.png
[11]: //images.ctfassets.net/ly2f59p4unnn/5RjSA6jgEXtXLJr01nhyGr/2e7c8e0406319dc35070ebdd7a6775d7/openapi_docs.png
[12]: //images.ctfassets.net/ly2f59p4unnn/2sSXFEuskuEw5iya8ttjko/05c01348a5670717ac6ebec92ff75f41/undraw_contract_uy56.png
[13]: https://fastapi.tiangolo.com/tutorial/sql-databases/
[14]: https://fastapi.tiangolo.com/features/#security-and-authentication
[15]: https://fastapi.tiangolo.com/tutorial/testing/
[16]: https://fastapi.tiangolo.com/advanced/async-tests/
[17]: //images.ctfassets.net/ly2f59p4unnn/1ifBzQ1MgLIQhmyIerXnWo/89944a23430cbacad62a24cf6f883f66/undraw_High_five_u364.png
[18]: https://maxongzb.activehosted.com/f/5
[19]: https://fastapi.tiangolo.com/
[20]: https://towardsdatascience.com/why-we-switched-from-flask-to-fastapi-for-production-machine-learning-765aab9b3679
[21]: https://medium.com/@tiangolo/introducing-fastapi-fdc1206d453f
[22]: https://youtu.be/5rWGWetiBHo
[23]: https://www.twilio.com/blog/build-secure-twilio-webhook-python-fastapi
[24]: https://swagger.io/blog/api-strategy/benefits-of-openapi-api-development/
[25]: https://undraw.co/