Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
RESTful Python API in 50 Lines or Less (Listens for HTTP Requests and Spits out JSON)
# 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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.