Building REST API in Python using FastAPI

Building REST API in Python using FastAPI

In this article I will discuss some basics about RESTful webservice and developing a web service in Python using Fast API framework.

First let’s see what a RESTful service is. REST stands for Representational state transfer. It is a standard for developing interactive applications that use web services. We have multiple architectural guiding constraints in developing RESTful services. For detailed information on RESTful services, I recommend to below resources:

·        https://en.wikipedia.org/wiki/Representational_state_transfer

·        https://flask-restful.readthedocs.io/en/latest/ (Flask is another Python framework for building web services)

What is FastAPI?

FastAPI is a modern high-performance web framework that with Python3.6+ based on standard Python. While there are many articles out there mentioning about performance of FastAPI, the FastAPI documentation itself has explained very well about the benchmarks and speed with comparison between Uvicorn, Starlette and FastAPI.

FastAPI is an API microframework with support to build APIs, data validation, Open API docs generation etc., that is developed using Starlette, yet another microframework. These run with the help of Uvicron, an ASGI server.

Below are the some of key features:

        ·        Fast: Very high performance, on par with NodeJS and Go (thanks to Starlette and Pydantic). One of the fastest Python frameworks available.

·        Fast to code: Increase the speed to develop features by about 200% to 300% *.

·        Fewer bugs: Reduce about 40% of human (developer) induced errors. *

·        Intuitive: Great editor support. Completion everywhere. Less time debugging.

·        Easy: Designed to be easy to use and learn. Less time reading docs.

·        Short: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.

·        Robust: Get production-ready code. With automatic interactive documentation.

·        Standards-based: Based on (and fully compatible with) the open standards for APIs: OpenAPI (previously known as Swagger) and JSON Schema.

·        estimation based on tests on an internal development team, building production applications.

You can get more details from FastAPI from here

 

Now let’s start developing a simple web service using FastAPI. I will be using VSCode for developing this simple web service. 

Let’s create a folder and name it ‘fastapi-hello-world    

Now open this empty folder in VSCode 

·        Not to corrupt my python environment, I will create a virtual environment using my base python 3.6. We need python 3.6+ for Fast API.

·        You can ignore below virtual env setup if you want to run on base python

·        Below is a command to create to a virtual environment from terminal:

py    python -m venv fastapi-env

This will create a folder fastapi-env with our python environment ready to use.


While that command is being executed a pop up will be displayed in VSCode, A new python environment is detected, would you like to use? You can select Yes, else we can use below command to activate our virtual environment.

·            fastapi-env\Scripts\activate


We need FastAPI package and an ASGI server to run our hello world web service. Here I will be using Uvicron to run fast api services. We need to run below commands to install fast API and uvicorn package

    pip install fastapi
    pip install uvicorn


Now we have installed all the required packages. Let’s start creating a microservice. We will create a python file main.py. First we need to import FastAPI package and initialize FastAPI

 

Below is code in main.py

from fastapi import FastAPI

 

app = FastAPI()

 

@app.get("/")

def hello_world():

    return {"hello""world"}

 

 

Note: you can mix def and async def in your path operation functions as much as you need and define each one using the best option for you. FastAPI will do the right thing with them.

 

Now let’s run this web service. We need to run below command in order to start uvicorn server:

    uvicorn main:app



Once the server is up and running you can open http://localhost:8000/ in any of your browser and it will display below json



Your hello world micro service is now up and running.

Interactive API docs

Now go to http://127.0.0.1:8000/docs.

You will see the automatic interactive API documentation (provided by Swagger UI). You can try executing your hello world service from here: 



Alternative API docs

And now, go to http://127.0.0.1:8000/redoc.

You will see the alternative automatic documentation (provided by ReDoc):


In my next articles I will come cover adding additional services, different HTTP methods, Fast API debugging and various other tips in optimizing services


Comments

Post a Comment

Popular posts from this blog

Connect Smartly to Your Baby With Owlet Sock