Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
Deploying ML Models as API using FastAPI
Next article icon

Deploying ML Models as API using FastAPI

Last Updated : 16 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Deployment usually the last step in any Data Science Project Pipeline, to be able to integrate your ML/DL model to a web application is quite an important task. There are many popular frameworks that can be used to do this task like Flask and Django. Django is usually used for large scale application and takes quite a bit time to set up that while Flask is usually your go-to for quickly deploying your model on a web app. Apart from the two mentioned there is another framework that is becoming quite popular, so much so that companies like Netflix and Uber are using it, and that framework is FastAPI. So let's understand what's making FastAPI so popular and how you can use it to deploy ML models as an API using it.

FastAPI vs Flask:

  • FastAPI is way faster than Flask, not just that it's also one of the fastest python modules out there.
  • Unlike Flask, FastAPI provides an easier implementation for Data Validation to define the specific data type of the data you send.
  • Automatic Docs to call and test your API(Swagger UI and Redoc).
  • FastAPI comes with built-in support for Asyncio, GraphQL and Websockets.

Installing FastAPI:

Installing FastAPI is the same as any other python module, but along with FastAPI you also need to install uvicorn to work as a server. You can install both of them using the following command:-

pip install fastapi uvicorn

Creating Basic API using FastAPI:

Before creating our ML model lets start by creating a basic API that's going to return us a simple message.

Python3
# Importing Necessary modules from fastapi import FastAPI import uvicorn  # Declaring our FastAPI instance app = FastAPI()  # Defining path operation for root endpoint @app.get('/') def main():     return {'message': 'Welcome to GeeksforGeeks!'}  # Defining path operation for /name endpoint @app.get('/{name}') def hello_name(name : str):      # Defining a function that takes only string as input and output the     # following message.      return {'message': f'Welcome to GeeksforGeeks!, {name}'} 

Testing Our API:

The above code defined all the path operation in the file that we'll name as basic-app.py.  Now to run this file we'll open the terminal in our directory and write the following command:-

uvicorn basic-app:app --reload

Now the above command follows the following format:-

  • basic-app refers to the name of the file we created our API in.
  • app refers to the FastAPI instance we declared in the file.
  • --reload tells to restart the server every time we reload.

Now after you run this command and go to http://127.0.0.1:8000/ you'll see the following in your browser.

You see this message because you told FastAPI to return this as Response when root path is called. One thing to note is that our message was a Python Dictionary but it was converted to JSON automatically. Now along with this you also have another endpoint in which you can get a custom string to be displayed in the message, to call that go to http://127.0.0.1:8000/herumb, here following message will be displayed in the browser.

Interactive API docs:

Now to get the above result we had to manually call each endpoint but FastAPI comes with Interactive API docs which can access by adding /docs in your path. To access docs for our API we'll go to http://127.0.0.1:8000/docs. Here you'll get the following page where you can test the endpoints of your API by seeing the output they'll give for the corresponding inputs if any. You should see the following page for our API.

Deploying our ML Model:

Building Our Model:

For this tutorial, we are going to use GuassianNB as our model and iris dataset to train our model on. To build and train our model we use the following code:

from sklearn.datasets import load_iris from sklearn.naive_bayes import GaussianNB  # Loading Iris Dataset iris = load_iris()  # Getting features and targets from the dataset X = iris.data Y = iris.target  # Fitting our Model on the dataset clf = GaussianNB() clf.fit(X,Y)

Now that we have our model ready we need to define the format of the data we are going to provide to our model to make the predictions. This step is import because our model works on numerical data, and we don't want to feed the data of any other type to our model, in order to do this we need to validate that the data we receive follows that norm. 

The Request Body:

The data sent from the client side to the API is called a request body. The data sent from API to the client is called a response body. 

To define our request body we'll use BaseModel ,in pydantic module, and define the format of the data we'll send to the API. To define our request body, we'll create a class that inherits BaseModel and define the features as the attributes of that class along with their type hints. What pydantic does is that it defines these type hints during runtime and generates an error when data is invalid. So let's create our request_body class:-

from pydantic import BaseModel  class request_body(BaseModel):     sepal_length : float     sepal_width : float     petal_length : float     petal_width : float

The Endpoint:

Now that we have a request body all that's left to do is to add an endpoint that'll predict the class and return it as a response :

@app.post('/predict') def predict(data : request_body):     test_data = [[             data.sepal_length,              data.sepal_width,              data.petal_length,              data.petal_width     ]]     class_idx = clf.predict(test_data)[0]     return { 'class' : iris.target_names[class_idx]}

And there we have our ML model deployed as an API. Now all that's left to do is test it out.

Testing our API:

To test our API we'll be using Swagger UI now to access that you'll just need to add /docs at the end of your path. So go to http://127.0.0.1:8000/docs. And you should see the following output:

Now click on the Try it Out button and enter the data you want the prediction for:

After you've entered all the values click on Execute, after this you can see your output under the responses section:

And as you can see we got our class as the response. And with that we have successfully deployed our ML model as an API using FastAPI.

Python3
from fastapi import FastAPI import uvicorn from sklearn.datasets import load_iris from sklearn.naive_bayes import GaussianNB from pydantic import BaseModel  # Creating FastAPI instance app = FastAPI()  # Creating class to define the request body # and the type hints of each attribute class request_body(BaseModel):     sepal_length : float     sepal_width : float     petal_length : float     petal_width : float  # Loading Iris Dataset iris = load_iris()  # Getting our Features and Targets X = iris.data Y = iris.target  # Creating and Fitting our Model clf = GaussianNB() clf.fit(X,Y)  # Creating an Endpoint to receive the data # to make prediction on. @app.post('/predict') def predict(data : request_body):     # Making the data in a form suitable for prediction     test_data = [[             data.sepal_length,              data.sepal_width,              data.petal_length,              data.petal_width     ]]          # Predicting the Class     class_idx = clf.predict(test_data)[0]          # Return the Result     return { 'class' : iris.target_names[class_idx]} 

Next Article
Deploying ML Models as API using FastAPI

H

herumbshandilya
Improve
Article Tags :
  • Machine Learning
  • AI-ML-DS
  • ML-deployment
  • AI-ML-DS With Python
Practice Tags :
  • Machine Learning

Similar Reads

    Machine Learning Tutorial
    Machine learning is a branch of Artificial Intelligence that focuses on developing models and algorithms that let computers learn from data without being explicitly programmed for every task. In simple words, ML teaches the systems to think and understand like humans by learning from the data.Machin
    5 min read

    Prerequisites for Machine Learning

    Python for Machine Learning
    Welcome to "Python for Machine Learning," a comprehensive guide to mastering one of the most powerful tools in the data science toolkit. Python is widely recognized for its simplicity, versatility, and extensive ecosystem of libraries, making it the go-to programming language for machine learning. I
    6 min read
    SQL for Machine Learning
    Integrating SQL with machine learning can provide a powerful framework for managing and analyzing data, especially in scenarios where large datasets are involved. By combining the structured querying capabilities of SQL with the analytical and predictive capabilities of machine learning algorithms,
    6 min read

    Getting Started with Machine Learning

    Advantages and Disadvantages of Machine Learning
    Machine learning (ML) has revolutionized industries, reshaped decision-making processes, and transformed how we interact with technology. As a subset of artificial intelligence ML enables systems to learn from data, identify patterns, and make decisions with minimal human intervention. While its pot
    3 min read
    Why ML is Important ?
    Machine learning (ML) has become a cornerstone of modern technology, revolutionizing industries and reshaping the way we interact with the world. As a subset of artificial intelligence (AI), ML enables systems to learn and improve from experience without being explicitly programmed. Its importance s
    4 min read
    Real- Life Examples of Machine Learning
    Machine learning plays an important role in real life, as it provides us with countless possibilities and solutions to problems. It is used in various fields, such as health care, financial services, regulation, and more. Importance of Machine Learning in Real-Life ScenariosThe importance of machine
    13 min read
    What is the Role of Machine Learning in Data Science
    In today's world, the collaboration between machine learning and data science plays an important role in maximizing the potential of large datasets. Despite the complexity, these concepts are integral in unraveling insights from vast data pools. Let's delve into the role of machine learning in data
    9 min read
    Top Machine Learning Careers/Jobs
    Machine Learning (ML) is one of the fastest-growing fields in technology, driving innovations across healthcare, finance, e-commerce, and more. As companies increasingly adopt AI-based solutions, the demand for skilled ML professionals is Soaring. Machine Learning JobsThis article delves into the Ty
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences