Easy APIs with python Flask.

Akhilesh Sharma
Jun 3, 2019 · 3 min read

Prerequisites: Basic python knowledge.

Flask is a web application framework written with Python language. Applications written with Flask can be as simple as a single .py file or it can have multiple modules with different functionalities.

In short a Flask application is an instance of the Flask class. For small applications we create a Flask instance globally. For large applications we instantiate the same in a function called as application factory( inside __init__.py). Any configuration or setup requirements are also added to this application factory.

As an example for this tutorial we will process some text using the TextBlob library. We will have some endpoints which will receive a request with text payload, and after processing , will respond with the processed text.

To start with, lets create a flask directory to save your files into.

mkdir flask

Now we will cd into this directory and create a api.py file.

cd flasktouch api.py

Lets start with a basic root(‘/’) route. Copy and paste the below mentioned code into the api.py file. This will expose a route “/” which can be accessed as a get request from the browser.

import osfrom flask import Flask, request, make_response, render_template
app = Flask(__name__)
@app.route(“/”, methods=[“GET”])
def home():
return ‘Hello World’
if __name__ == ‘__main__’:

We can now start the flask server using the command below

python api.py

This will start the server at port 5000. If you open your browser at url — you should be able to see “Hello World” as the output.

Now lets write a method for an API endpoint to accept a text and return a text with correct spellings (in case if there are any spelling mistakes in your text )

@app.route(‘/endpoint’,methods=[‘POST’])def endpoint():
text = TextBlob(request.json[‘text’])
corrected_text = text.correct().string
return json.dumps({“corrected_text”: corrected_text})

Now as in the screenshot above, you have to send the request to you endpoint url and you should get a corrected text as the response.Like here in this example, we are sending the request “Havv a nice day!” and we get “Have a nice day ” in response.

Now lets create endpoints for noun phrase extraction ,detection of language and translation to other languages.

So this is the final code we have after writing all the methods above.

import os
from flask import Flask, request, make_response, render_template
from textblob import TextBlob
import IPython
import json
app = Flask(__name__)#sample root route
@app.route(“/”, methods=[“GET”])
def home():
return ‘Hello World’

#request example — Correct spellings in a text
#{“text”: “Havv a nice day!”}
def spelling_endpoint():
text = TextBlob(request.json[‘text’])
corrected_text = text.correct().string
return json.dumps({“corrected_text”: corrected_text})
#response {“corrected_text”: “Have a nice day!”}

# request example — Get nouns in a sentence
#{“text”: “Ruby is an intrepreted language!”}
def noun_phase_extraction():
text = TextBlob(request.json[‘text’])
nouns = “,”.join(list(text.noun_phrases))
return json.dumps({“nouns_in_text”: nouns})
#response {“nouns_in_text”: “ruby”}

#request example — Translate a text to another language
# {“text”: “Today is a good day”,”lang”: “hi”}
def translate():
en_blob = TextBlob(request.json[‘text’])
translated_text =en_blob.translate(to=request.json[‘lang’]).string
return json.dumps({“translated_text”: translated_text})
#response {“translated_text”: “आज एक अच्छा दिन है”}

#request example — Detect the language a text is written in
#{“text”: “Today is a good day”}
def detect_language():
en_blob = TextBlob(request.json[‘text’])
language = en_blob.detect_language()
return json.dumps({“language”: language})
#response {“language”: “en”}
if __name__ == ‘__main__’:

You can add these to your app.py file. Note: you will need to install some additional packages for the processing like

python -m textblob.download_corpora

All these endpoints can be requested using a REST client like Postman or Advanced Rest Client.

All the APIs will return processed text data in JSON format.
We can consume these APIs with some front end framework to display it to the user.

You can create really big projects with flask with complete authentication and authorisation.

You can explore more on Flask and TextBlob. The official documentation is really helpful.

Getting started with Flask is extremely easy.

Akhilesh Sharma

Written by

Hey, I like working on new concepts and follow an approach of keeping things as simple as possible. Appreciates neat architecture and intelligent design.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade