How to Use FastAPI in Python

Introduction

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 sampleApi.py

#filename: sampleApi.py
from fastapi import FastAPI
app = FastAPI()

@app.get("/add")
def add(a, b):
    return int(a) + int(b)

@app.get("/sub")
def sub(a, b):
    if a > b:
        return int(a) - int(b)
    else:
        return int(b) - int(a)

@app.get("/mul")
def mul(a, b):
    return int(a) * int(b)

@app.get("/div")
def div(a, b):
    if a > b:
        return int(a) / int(b)
    else:
        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

http://127.0.0.1:8000/<endpoint_name>?a=<param1>&b=<param2>

For example,

http://127.0.0.1:8000/mul?a=2&b=44 
#will return you 88

Summary

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


Similar Articles