I'm attempting to make the simplest possible REST API server and client, with both the server and client being written in Python and running on the same computer.
From this tutorial:
https://blog.miguelgrinberg.com/post/designing-a-restful-api-with-python-and-flask
I'm using this for the server:
# server.py
from flask import Flask, jsonify
app = Flask(__name__)
tasks = [
{
'id': 1,
'title': u'Buy groceries',
'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
'done': False
},
{
'id': 2,
'title': u'Learn Python',
'description': u'Need to find a good Python tutorial on the web',
'done': False
}
]
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
if __name__ == '__main__':
app.run(debug=True)
If I run this from the command line:
curl -i http://localhost:5000/todo/api/v1.0/tasks
I get this:
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 317
Server: Werkzeug/0.16.0 Python/3.6.9
Date: Thu, 05 Mar 2020 02:45:59 GMT
{
"tasks": [
{
"description": "Milk, Cheese, Pizza, Fruit, Tylenol",
"done": false,
"id": 1,
"title": "Buy groceries"
},
{
"description": "Need to find a good Python tutorial on the web",
"done": false,
"id": 2,
"title": "Learn Python"
}
]
}
Great, now my question is, how can I write a Python script using requests to obtain the same information?
I suspect this is the proper idea:
# client.py
import requests
url = 'http://todo/api/v1.0/tasks'
response = requests.get(url,
# what goes here ??
)
print('response = ' + str(response))
However as you can see from my comment, I'm not sure how to set up the parameters for requests.get
.
I attempted to use this SO post:
Making a request to a RESTful API using python
as a guideline however it's not clear how to adjust the formatting per the message change.
Can provide a brief description of how to set up params to pass into requests.get
and suggest the necessary changes to get the client example above working? Thanks!
--- Edit ---
Something else I can mention is that I got the client to work using Postman pretty easily, I'm just not sure how to set up the syntax in Python:
--- Edit ---
Based on icedwater's response below, this is complete, working code for the client:
# client.py
import requests
import json
url = 'http://localhost:5000/todo/api/v1.0/tasks'
response = requests.get(url)
print(str(response))
print('')
print(json.dumps(response.json(), indent=4))
result:
<Response [200]>
{
"tasks": [
{
"description": "Milk, Cheese, Pizza, Fruit, Tylenol",
"done": false,
"id": 1,
"title": "Buy groceries"
},
{
"description": "Need to find a good Python tutorial on the web",
"done": false,
"id": 2,
"title": "Learn Python"
}
]
}