How to create your basic API using FastAPI in 2022

Rushikesh Naik
3 min readAug 1, 2022

--

Couple of lines that much it will take.

You have completed the main part of your project & now you are looking to make it more accessible. Be it Data Science or AI / ML project or any other software engineering project where you are providing service to your end user. You need to create an end point where your user can access the service. So in this article we’re going to look into how to create the API within few lines of code with FastAPI.

credit : fastapi.tiangolo.com

Let’s get started, firstly we are going to need our python file which will be having fastapi instance to create our app. I have created a file named “main.py” from which I will be instantiating fastapi.

If you are following along with me then you can just create main.py file and add the below code(link for the repo can be found in last part of the article)

So this file is basically everything your api is going to need, I will try to explain it. Firstly we have imported fastapi, and instantiated our app variable with fastapi() call.

app = FastAPI() # instantiating fastapi 

After that we need to use decorators provided by fastapi i.e. `@ app.get`, this decorators basically tells that the function below this decorator takes a get request and provides output. we are going to pass the string in `get` for the path url that we are going to access the API on.

# home page
@app.get('/')
def home():
return {
"message" : "we are in home page"
}

To run the fastapi main.py file, we need to install Uvicorn and run the server

# installing Uvicorn 
pip install uvicorn
# to the running the application
uvicorn main:app --host 0.0.0.0 --port 80
# after running this, if there are no error then you will get the below message at localhost

Now this will take care of returning a message in json format you can see below.

Let’s create a add.py file with addition function. This will help us to understand how we can provide basic functionality with fastAPI (I will be covering most of the fastapi functionality so stay tuned)

We have created this dummy add function, I have created new app.get request with ‘/add’ url with local host. You can check the expected output :

github link : https://github.com/rushikeshnaik779/fastAPI_blg/tree/master/fastapi_1

References :

https://www.udemy.com/course/fastapi-the-complete-course/

--

--

Rushikesh Naik

MLE who loves to learn & use new tech and talk about it.