Skip to content

Instantly share code, notes, and snippets.

@ajinux
Last active July 25, 2017 21:28
Show Gist options
  • Save ajinux/345477f81260fd6a60c25a301a8e0490 to your computer and use it in GitHub Desktop.
Save ajinux/345477f81260fd6a60c25a301a8e0490 to your computer and use it in GitHub Desktop.
JSON API in Python flask

JSON API

Question

Question Code:JSON_API
                    Create a JSON API server takes a string and returns response ‘acks’ when the input is number ‘acki’ when the input is a string and has a JSON field in the response which divides the requested object into two.

Input - 1

input1

Output - 1

output1

Input - 2

input2

Output - 2

input2

dependencies

  • Python 2.7
  • flask 0.11.1 (python package)
#!/usr/bin/python
#python 2.7
from flask import Flask, request, json, render_template
app = Flask(__name__)
app.debug = True
@app.route('/', methods=['POST', 'GET'])
def index():
if request.method == "GET":
return render_template('welcome.html')
else:
inp = request.form['input']
try:
# check wheather input is convertable to int or not
int(inp)
result = 'aski'
except ValueError:
result = 'asks'
data = {'JSON': result}
# sets appropriate headers for json response
response = app.response_class(
response=json.dumps(data),
status=200,
mimetype='application/json'
)
return response
if __name__ == '__main__':
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment