How to Build a RESTful API in Python with Flask in 50 Lines or Less

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Really simple example of how to build an API with Python and Flask that listens for HTTP requests and spits out JSON. The hard part of all of this is building the JSON with python. For really simple JSON we can just use a dictionary. However, where things get complicated is if you want your JSON objects to contain objects. The work around I’ve found is to simply create a dictionary of dictionaries, where we will use dictionaries instead of objects. In the example below first_category, second_category, and third_category would normally be represented as objects, but have been converted to dictionaries instead:

# Import Flask
from flask import Flask, render_template, request, jsonify, session, redirect, url_for, Response
app = Flask(__name__)
# REFERENCE: http://blog.luisrei.com/articles/flaskrest.html
@app.route('/dictionary-to-json-test', methods=['GET', 'POST'])
def dictionary_to_json_test():
list_of_categories = []
first_category = {
"name": "Fast Food",
"number_of_transactions": 13,
"amount_spent": 427.33
}
second_category = {
"name": "Restaurants",
"number_of_transactions": 1,
"amount_spent": 54.0
}
third_category = {
"name": "Entertainment",
"number_of_transactions": 2,
"amount_spent": 125.0
}
list_of_categories.append(first_category)
list_of_categories.append(second_category)
list_of_categories.append(third_category)
dictionary_of_dictionaries = {
"category": list_of_categories
}
# Convert Dictionary to JSON
json_obj = json.dumps(dictionary_of_dictionaries)
# Create Response Object
response_obj = Response(json_obj, status=200, mimetype='application/json')
# Return JSON (Response Object)
return response_obj
if __name__ == "__main__":
app.run()
 

topherPedersen