calling web services from python
We will use our own web service we built earlier to interact with, run this in a separate terminal
from flask import Flask, jsonify, request, abort app=Flask(__name__) data=[{'fname':'Steve', 'lname':'Jobbs'},{'fname':'Bill', 'lname':'Gates'}] @app.route('/createperson', methods=['POST']) def create_person(): print(request.json) if not request.json or not 'person' in request.json: abort(400) data.append(request.json['person']) return jsonify({'data' : data}), 201 @app.route('/data', methods=['GET']) def get_data(): return jsonify({'data' : data}) @app.route('/data/', methods=['GET']) def get_data_byid(id): return jsonify({'data' : data[id]}) app.run(debug = True)
Calling GET
We have previously looked at fetching JSON from weather web services, here we will apply same concept to extract the JSON from our own web service
import urllib.request import json from pprint import pprint page = urllib.request.urlopen("http://127.0.0.1:5000/data") content=page.read() content_string = content.decode("utf-8") json_data = json.loads(content_string) pprint(json_data)
Output:
{'data': [{'fname': 'Steve', 'lname': 'Jobbs'}, {'fname': 'Bill', 'lname': 'Gates'}, {'fname': 'Sergey', 'lname': 'Brin'}]}
Exercise: how would I print just the first names?
for item in json_data['data']: print(item['fname'])
calling POST
import httplib2 from json import dumps, loads url = "http://127.0.0.1:5000/createperson" data = dumps({"person":{"fname":"Larry", "lname":"Page"}}) header = {"Content-Type":"application/json","User-Agent":"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"} http=httplib2.Http() response = http.request(url,"POST",headers=header,body=data)
Validate the new data has been added by invoking the http://127.0.0.1:5000/data