Using Python’s Flask to Build a Basic API

Prerequisites

The only prereq to understanding this article is knowing git if you want to get the code, but it isn’t necessary. I’m starting this from ground zero. If you’re just getting started with Python, be sure to read “Getting Started With Python Right!” and “Unbreaking Python Through Virtual Environments” about setting up your environment. These two entries cover enough to ensure you won’t end up with broken, conflicted, and convoluted Python environments.

Mission: Build a Flask based API.

This post is about a singular thing, building an API with Flask. It won’t be about data modeling, databases, or wrapping middleware into the mix. It’s pure and simple Flask, with just the bare necessities needed to get an API working and responding appropriately requests.

Flask Installation

I’ve already setup and have an environment for Python, based on a virtualenv setup like I stepped through in this post. The versions in my environment include v3.7.3 Python.

$ python --version
Python 3.7.3
$ which python
/Users/adron/Codez/python-env-examples/bin/python
pip install Flask

First Code

Next step is to write something that executes with Flask. The easiest thing is just creating a standard hello world with a root URL API end point with Flask. To do this I created a file I named server.py and added the following code.

from flask import Flask
app = Flask(__name__)
@app.route('/')
def heyo_mofo():
return 'Heyo, Sup!'
export FLASK_APP=server.py
flask run
export FLASK_ENV=development
export FLASK_APP=server.py
flask run

Routing With Routes

Now that I’ve got a basic hello world working, let’s add some more routes that go beyond merely a “heyo sup?”. For the next example I’ll add

from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/datum')
def hello():
return 'The data to provide!'
@app.route('/unit/<uuid:unit_id>')
def show_unit(unit_id):
return 'Unit ID %d, albeit this would usually be used to get the post details and body from a database to present.' % unit_id
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
return 'Showing the subpath after the /path/ - Subpath %s' % escape(subpath)
@app.route('/efforts/')
def projects():
return 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam scelerisque tellus sed magna pulvinar egestas. Donec vitae diam in eros porta mollis. Vestibulum sagittis lorem id dolor luctus, quis tincidunt nulla dictum. Etiam ac vulputate massa. Nullam aliquet arcu imperdiet, mattis mi sed, rutrum lectus. Phasellus viverra leo et mi dapibus tincidunt. Nulla facilisi. Cras eget metus turpis. Etiam a elit arcu. Pellentesque ac eros ligula.'
@app.route('/about')
def about():
return 'Morbi rhoncus congue justo id malesuada. Mauris semper mattis dui. Etiam sodales dui vitae tincidunt iaculis. Nam id velit accumsan, aliquam lorem ac, ultrices nisl. Aenean non lectus tellus. Mauris rutrum metus ut condimentum efficitur. Nulla a dolor felis. Aenean congue turpis vitae felis commodo, vitae blandit dolor varius. Duis faucibus neque dolor, eu sollicitudin lacus lacinia vel. Etiam hendrerit, nibh vitae porta vestibulum, odio metus sollicitudin justo, in lobortis metus nisi fermentum justo. Cras pellentesque vel nunc posuere fermentum.'
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Index Page'
@app.route('/datum')
def hello():
return 'The data to provide!'
@app.route('/unit/<uuid:unit_id>')
def show_unit(unit_id):
return 'Unit ID %d, albeit this would usually be used to get the post details and body from a database to present.' % unit_id
@app.route('/path/<path:subpath>')
def show_subpath(subpath):
return 'Showing the subpath after the /path/ - Subpath %s' % escape(subpath)
NameError: name ‘escape’ is not defined
from glob import escape

Converters

A quick interruption, here are the converter types available:

@app.route('/efforts/')
def projects():
return 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam scelerisque tellus sed magna pulvinar egestas. Donec vitae diam in eros porta mollis. Vestibulum sagittis lorem id dolor luctus, quis tincidunt nulla dictum. Etiam ac vulputate massa. Nullam aliquet arcu imperdiet, mattis mi sed, rutrum lectus. Phasellus viverra leo et mi dapibus tincidunt. Nulla facilisi. Cras eget metus turpis. Etiam a elit arcu. Pellentesque ac eros ligula.'
@app.route('/about')
def about():
return 'Morbi rhoncus congue justo id malesuada. Mauris semper mattis dui. Etiam sodales dui vitae tincidunt iaculis. Nam id velit accumsan, aliquam lorem ac, ultrices nisl. Aenean non lectus tellus. Mauris rutrum metus ut condimentum efficitur. Nulla a dolor felis. Aenean congue turpis vitae felis commodo, vitae blandit dolor varius. Duis faucibus neque dolor, eu sollicitudin lacus lacinia vel. Etiam hendrerit, nibh vitae porta vestibulum, odio metus sollicitudin justo, in lobortis metus nisi fermentum justo. Cras pellentesque vel nunc posuere fermentum.'

--

--

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
Adron Hall

Adron Hall

Software dev, data, heavy metal, transit, economics, freethought, atheism, cycling, livability, beautiful things & adrenaline junkie.