Create an API in Flask and deploy it online – 2024

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)
  • This is a very basic Flask Code.
  • In Line 1 we are simply importing the required packages from Flask Library.
  • In Line 4 we are defining our Flask app.
  • In lines 7-12 we are defining our main function. It just extracts num1 and num2 from the JSON received in the request and returns their sum as the response.
  • In lines 15-16 we are simply running the Flask app.

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

Create an API in Flask

Testing the API in Postman

Create an API in Flask

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.

Leave a Reply

Your email address will not be published. Required fields are marked *