Create an API in Flask and deploy it online

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.

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

Read the full blog here — https://machinelearningprojects.net/create-an-api-in-flask/

Checkout the video here — https://youtu.be/aPXS-pD7F58

Code for building 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.

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 requestsurl = '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 projects, deep learning projects, computer vision projects, NLP projects, and Flask projects at machinelearningprojects.net.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store