Created
August 7, 2019 05:00
-
-
Save topherPedersen/8311e94bb6544724aec5e1fc98751963 to your computer and use it in GitHub Desktop.
RESTful Python API in 50 Lines or Less (Listens for HTTP Requests and Spits out JSON)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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