Skip to content

Instantly share code, notes, and snippets.

@iamvon
Last active April 13, 2019 18:57
Show Gist options
  • Select an option

  • Save iamvon/4f923a9758fca28d2dafea6b2e4c229b to your computer and use it in GitHub Desktop.

Select an option

Save iamvon/4f923a9758fca28d2dafea6b2e4c229b to your computer and use it in GitHub Desktop.
Demo Python Flask API

How to run it ?

Open your Terminal

1) Install necessary modules

pip3 install flask requests jsonpickle

2) Start Flask server

export FLASK_APP=server.py
flask run 

3) Run client

python3 client.py 
import requests
import json
addr = 'http://localhost:5000'
test_get = addr + '/v1/api/test_get'
test_post = addr + '/v1/api/test_post'
# Prepare headers for http request
content_type = 'application/json'
headers = {'content-type': content_type}
# Query to test_get API using GET http method
get_response = requests.get(test_get)
# decode response
print('Response of GET method: ', get_response.json())
# prepare body/payload for http request
payload = {
"message": "This is a POST request message!",
}
payload = json.dumps(payload)
loaded_payload = json.loads(payload)
# Query to test_post API using GET http method
post_response = requests.post(test_post, '', json=loaded_payload)
# decode response
print('Response of POST method: ', post_response.json())
from flask import Flask, request, Response, send_file
import jsonpickle
import json
import ast
import time
app = Flask(__name__)
baseURL = 'http://localhost:5000'
get_route = '/v1/api/test_get'
post_route = '/v1/api/test_post'
# Implement get_route API using GET http method
@app.route(get_route, methods=['GET'])
def test_get():
response = {'get_message': 'This is a GET response message!', 'status': '200'}
print(type(response))
response_pickled = jsonpickle.encode(response)
return Response(response=response_pickled, status=200, mimetype="application/json")
# Implement post_route API using POST http method
@app.route(post_route, methods=['GET', 'POST'])
def test_post():
loaded_body = parse_json_from_request(request)
message = loaded_body['message']
message_response = message+' And this a POST response message!'
response = {'post_message': message_response, 'status': '200'}
response_pickled = jsonpickle.encode(response)
return Response(response=response_pickled, status=200, mimetype="application/json")
def parse_json_from_request(request):
body_dict = request.json
body_str = json.dumps(body_dict)
loaded_body = ast.literal_eval(body_str)
return loaded_body
if __name__ == "__main__":
# start flask app
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment