Creating a Flask API with Python

Jihan Jeeth
2 min readJun 29, 2021

--

Data science is taking over the world these days. Machine Learning and Artificial Intelligence takes a major part of the human’s day to day life.

Python plays a major part in all ML and AI related progressions. Even a simple prediction model needs an API to send requests and get responses. This communication with the model can be done easily with Flask.

Flask allows your application to run as a server and make communications through APIs. This is the easiest approach to create communications between the client and the model. Lets have a step by step look at the process.

First we will require to install Flask locally or into the project depending on the way that you are planing to execute the application. If you’re using PyCharm, you can add by navigating to Settings -> Project -> Python Interpreter and install the library. If not you can install using pip or any other preferred method.

After installing you should import the library and you are good to go.

Now lets start initializing an app.

app = flask.Flask(__name__)

After initialization you should annotate a method to a specific and unique route to be accessed outside.

@app.route(‘/hello_world’, methods=[‘GET’])

Following that, we should name the method we want to be executed on the API call.

def main():
return("Hello World")

Finally we can specify the port number that we want the application to execute.

if __name__ == ‘__main__’:
app.run(port=5000)

And that’s about it. Now you have a basic python-flask application. Note an important point here. In the last code segment I have provided, it contains two underscores. Do not add one underscore and debug for hours like I did on my first attempt.

You can run this app and try a simple get request. It should respond to you with a Hello World message.

There’s a few more things you can do to improve this. You can do post requests and you can make communications secure. Will see about them in the next blog.

Kudos.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Jihan Jeeth
Jihan Jeeth

Written by Jihan Jeeth

SE at WSO2 | Interested in blockchain and ML

No responses yet

Write a response