Skip to content

Instantly share code, notes, and snippets.

@i3p9
Created May 6, 2022 21:19
Show Gist options
  • Save i3p9/51936bcdf946f65b46fd997b170c51ca to your computer and use it in GitHub Desktop.
Save i3p9/51936bcdf946f65b46fd997b170c51ca to your computer and use it in GitHub Desktop.
Flask: Get up and running with GET/POST
=import json
from flask import Flask
from flask import request
from responses import get_cat_fact, get_activity
app = Flask(__name__)
# EXAMPLE REQUEST: GET 127.0.0.1:5000/
@app.route('/getname', methods=['GET'])
def index():
return json.dumps({'name': 'alice',
'email': '[email protected]'})
# EXAMPLE REQUEST: POST 127.0.0.1:5000/json-example Data:
# {
# "language" : "Python",
# "framework" : "Flask",
# "website" : "Scotch",
# "version_info" : {
# "python" : "3.9.0",
# "flask" : "1.1.2"
# },
# "examples" : ["query", "form", "json"],
# "boolean_test" : true
# }
@app.route('/json-example', methods=['POST'])
def json_example():
request_data = request.get_json()
language = request_data['language']
framework = request_data['framework']
python_version = request_data['version_info']['python']
example = request_data['examples'][0]
boolean_test = request_data['boolean_test']
return '''
The language value is: {}
The framework value is: {}
The Python version is: {}
The item at index 0 in the example list is: {}
The boolean value is: {}'''.format(language, framework, python_version, example, boolean_test)
# EXAMPLE REQUEST: POST 127.0.0.1:5000/ Data: {"data" : "cat"}
@app.route('/', methods=['POST'])
def facts():
request_data = request.get_json()
fact_or_bored = request_data['data']
if fact_or_bored == "cat":
return '''{}'''.format(get_cat_fact())
elif fact_or_bored == "bored":
return '''{}'''.format(get_activity())
else:
return '''no data found'''
app.run()
flask
json
reqeusts
import requests
def get_cat_fact():
api_url = 'https://catfact.ninja/fact'
response = requests.get(api_url)
data = response.json()
return data["fact"]
def get_activity():
api_url = 'https://www.boredapi.com/api/activity'
response = requests.get(api_url)
data = response.json()
return data["activity"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment