A Beginner’s Guide to FastAPI: Creating APIs for Data Science

Posted by


FastAPI is a highly efficient web framework for building APIs in Python. It is based on asynchronous programming, making it more performant than traditional synchronous web frameworks. FastAPI is gaining popularity within the data science community due to its ease of use, speed, and support for automatic API documentation generation.

In this tutorial, we will cover the basics of FastAPI and show you how to create APIs using FastAPI for data science applications.

Prerequisites:
Before diving into FastAPI, make sure you have Python installed on your local machine. You can check your Python version by running the following command in your terminal or command prompt:

python --version

If you don’t have Python installed, you can download it from the official Python website.

Installing FastAPI:
To install FastAPI, you can use pip, Python’s package manager. Run the following command in your terminal or command prompt:

pip install fastapi

Additionally, you will also need to install uvicorn, a lightning-fast ASGI server implementation, to run your FastAPI application. You can install uvicorn using pip:

pip install uvicorn

Creating Your First FastAPI Application:
Now that you have installed FastAPI and uvicorn, you can create your first FastAPI application. Start by creating a new Python file, for example, app.py, and open it in your preferred code editor.

Begin by importing the necessary components from FastAPI:

from fastapi import FastAPI

Next, create an instance of the FastAPI class:

app = FastAPI()

Now, you can define a simple API endpoint using a Python function. Decorate the function with the app.get decorator to specify the HTTP method and the endpoint path:

@app.get("/")
def read_root():
    return {"message": "Hello, World!"}

This function will return a JSON response with the message "Hello, World!" when you access the root endpoint of your FastAPI application.

Running Your FastAPI Application:
To run your FastAPI application, use uvicorn to serve your application. Navigate to the directory where your app.py file is located and run the following command:

uvicorn app:app --reload

This command instructs uvicorn to run your FastAPI application, with app referring to the name of your FastAPI instance in app.py.

Open your web browser and enter http://localhost:8000 in the address bar. You should see the message "Hello, World!" displayed on the page.

Congratulations! You have successfully created your first FastAPI application.

Defining API Endpoints:
In a real-world data science application, you may need to create multiple API endpoints to perform different tasks. FastAPI allows you to define endpoints for different HTTP methods and paths with ease.

Let’s create a simple API endpoint that calculates the square of a given number. Modify your app.py file as follows:

@app.get("/square/{num}")
def calculate_square(num: int):
    return {"result": num ** 2}

In this example, we define a new API endpoint at /square/{num} that takes a number as a parameter and returns the square of that number in the response.

Accessing this endpoint in your browser or using a tool like Postman will allow you to input a number and see the square of that number as the output.

Documenting Your API with Swagger UI:
One of the key features of FastAPI is its automatic generation of OpenAPI documentation for your APIs. FastAPI uses Swagger UI to provide an interactive documentation interface for your API endpoints.

To access the autogenerated documentation, navigate to http://localhost:8000/docs in your web browser. You will see a user-friendly interface displaying all your API endpoints, complete with input parameters, responses, and example payloads.

FastAPI provides detailed configuration options for customizing the autogenerated documentation. You can add descriptions, tags, and additional metadata to your API endpoints to enhance the documentation further.

Conclusion:
FastAPI is a powerful web framework for building APIs in Python, particularly well-suited for data science applications. In this tutorial, you learned the basics of FastAPI, how to create API endpoints, run your FastAPI application, and document your APIs using Swagger UI.

With FastAPI’s high performance, ease of use, and automatic documentation generation, you can develop robust and efficient APIs for your data science projects. Give FastAPI a try and experience the benefits of building APIs at lightning speed!

0 0 votes
Article Rating
41 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@arpitqw1
2 months ago

do not change accent in between. 😉

@savagehalt1555
2 months ago

Bhai at least explain that @app.get('/") is a decorator and a brief note on what decorators are… Otherwise good vid.

@hardishah3188
2 months ago

but u didnt show what is there in app.py

@veereshh3258
2 months ago

Sir Now django support both asgi and wsgi right?

@syedsiddiq4450
2 months ago

anyone please tell me can we use this in jupyter

@itishreepanda487
2 months ago

Sir my uvicorn is not recognised as internal and external command

@lord-qk3bx
2 months ago

Thank you so much! About to migrate my whole codebase from flask to fastapi!

@myhopefaith
2 months ago

thank you so much sir for these videos …u are decoding the black box that was deployment & making ppl confident in end to end proj delivery …u have made it very simple & easy to understand …

@neclis7777
2 months ago

Sir, that's amazing help. Thanks a lot !

@dharikarsath8852
2 months ago

Hi, I have used column transformer in my model so I have to pass dataframe of one row as a input to prediction, but I was not able to do that, so my question is how to pass one row of dataframe instead of list of list? @Krishnaik and others? help me if you know thanks

@aqibfayyaz1619
2 months ago

No words sir❤

@vashistnarayansingh5995
2 months ago

how fast api handles multiple requests, as we have threading as a parameter in flask to handle multiple request how does fast api do it?

@ipvikas
2 months ago

Using 'FASTAPI' in Google colab is comparatively easy:

#step 1: import

!pip install colabcode -q

!pip install fastapi -q

from colabcode import ColabCode

from fastapi import FastAPI

cc = ColabCode(port=12000, code=False)

app = FastAPI() #step2: instance

@app.get('/') #step4: Decorate

def index():

return 'Hello World' #step3: function

cc.run_app(app=app)

# Once it is executed and we get the .io URL, just add '/docs' at the end of the URL i.e. XYZ.io/docs

@chandraprakashsingh...9282
2 months ago

Sir how to add Html page that is integrate front end?

@chandraprakashsingh...9282
2 months ago

Thanku so much sir I came across this today

@footballforfun2054
2 months ago

how to choose port no. and host?

@user-or7ji5hv8y
2 months ago

Looking forward to more FastAPI videos

@nishas2134
2 months ago

S

@AJAYKUMAR-or2fx
2 months ago

I am getting error while running uvicorn main:app –reload. Error is "'uvicorn' is not recognized as an internal or external command, operable program or batch file". Please help

@footballforfun2054
2 months ago

how to get the local host and port of our device?