How to Use FastAPI in Python


FastAPI is API developing framework. To quick start, the API development FastAPI framework is very helpful. It is a high performance python coded framework.

Without being late, let's start. In the next 2 minutes, your API will be ready to play. As an example, we will start with the calculator API.

To start with FastAPI in python, run the below commands one by one.

Always start your project by creating a virtual environment, so we will never miss any dependency.

Step 1

To create a virtual environment, run the command,

 pipenv shell

Step 2

Install dependencies by running the below commands.

pipenv install fastapi 
pipenv install uvicorn

FastAPI will provide the required support to write a code, and Uvicorn will help you run the FastAPI.

Step 3

Below is the sample calculator API. Create filename as

from fastapi import FastAPI
app = FastAPI()

def add(a, b):
    return int(a) + int(b)

def sub(a, b):
    if a > b:
        return int(a) - int(b)
        return int(b) - int(a)

def mul(a, b):
    return int(a) * int(b)

def div(a, b):
    if a > b:
        return int(a) / int(b)
        return int(b) / int(a)

Step 4

To start API, run the below command

uvicorn sampleApi:app --reload

Now start playing with API. Using URL as<endpoint_name>?a=<param1>&b=<param2>

For example, 
#will return you 88


I hope it helps to understand the basics to kick start the API development.

Similar Articles