Site icon Machine Learning Projects

Create an API in Flask and deploy it online – 2022

Machine Learning Projects

Hey guys, in this blog we will see how we can Create an API in Flask and deploy it online so that whenever we hit this API either from Postman or from a Python Code, it returns the response successfully.

Checkout the Video Here – https://youtu.be/aPXS-pD7F58

So without any further due, let’s do it…

Code Files to Create an API in Flask

This is a very basic API written in Flask which just receives 2 numbers num1 and num2 as arguments and returns their sum as the response.

app.py

#Create an API in Flask

from flask import Flask,request


app = Flask(__name__)


@app.route('/',methods=['GET','POST'])
def home():
    num1 = int(request.json['num1'])
    num2 = int(request.json['num2'])
    
    return f'The sum of {num1} and {num2} is {num1+num2}'


if __name__ == '__main__':
    app.run(debug=True)

Let’s Test the API

Python Code for testing the API

import requests

url = 'http://127.0.0.1:5000/'
myinp = {'num1': 1,'num2': 2}

x = requests.post(url, json = myinp)

print(x.text)

Output

Testing the API in Postman

NOTE: For the sake of simplicity I am running this API currently on the localhost, but you can deploy it online and use it from anywhere in the world.

Refer to this article for deploying it online – How to Deploy a Flask app online using Pythonanywhere

And this is how you can Create an API in Flask…

So this is all for this blog folks. Thanks for reading it and I hope you are taking something with you after reading this and till the next time …

Check out my other machine learning projectsdeep learning projectscomputer vision projectsNLP projects, and Flask projects at machinelearningprojects.net.

Exit mobile version