How to make a simple Python REST server and client?

2024/9/16 23:13:55

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.pyfrom flask import Flask, jsonifyapp = 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.pyimport requestsurl = '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:

enter image description here

--- Edit ---

Based on icedwater's response below, this is complete, working code for the client:

# client.pyimport requests
import jsonurl = '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"}]
}
Answer

From help(requests.get):

Help on function get in module requests.api:get(url, params=None, **kwargs)Sends a GET request.:param url: URL for the new :class:`Request` object.:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.:param \*\*kwargs: Optional arguments that ``request`` takes.:return: :class:`Response <Response>` object:rtype: requests.Response

so I would say requests.get(url) would be enough to get a response. Then look at either the json() or data() functions in response depending on what the API is expected to return.

So for the case of a JSON response, the following code should be enough:

import requests
import jsonurl = "https://postman-echo.com/get?testprop=testval"
response = requests.get(url)
print(json.dumps(response.json(), indent=4))

Try the above code with an actual test API.

https://en.xdnf.cn/q/72668.html

Related Q&A

Histogram fitting with python

Ive been surfing but havent found the correct method to do the following.I have a histogram done with matplotlib:hist, bins, patches = plt.hist(distance, bins=100, normed=True)From the plot, I can see …

Subtract each row of matrix A from every row of matrix B without loops

Given two arrays, A (shape: M X C) and B (shape: N X C), is there a way to subtract each row of A from each row of B without using loops? The final output would be of shape (M N X C).Example A = np.ar…

Programmatically setting access control limits in mosquitto

I am working on an application that will use mqtt. I will be using the python library. I have been leaning towards using mosquitto but can find no way of programmatically setting access control limits …

Optimizing cartesian product between two Pandas Dataframe

I have two dataframes with the same columns:Dataframe 1:attr_1 attr_77 ... attr_8 userID John 1.2501 2.4196 ... 1.7610 Charles 0.0000 1.0618 ... 1.4813 Genarit…

Tensorflow: open a PIL.Image?

I have a script that obscures part of an image and runs it through a prediction net to see which parts of the image most strongly influence the tag prediction. To do this, I open a local image with PIL…

Django: Saving to DB from form example

It seems I had difficulty finding a good source/tutorial about saving data to the DB from a form. And as it progresses, I am slowly getting lost. I am new to Django, and please guide me. I am getting e…

eval(input()) in python 2to3

From the Python 2to3 doc:input:Converts input(prompt) to eval(input(prompt))I am currently trying to learn Python 3 after a few years working with Python 2. Can anybody please explain why the tool inse…

Post XML file using Python

Im new to Python and in need of some help. My aim is to send some XML with a post request to a URL, which is going to trigger a SMS being sent. I have a small XML document that I want to post to the UR…

Python TypeError: __init__() got multiple values for argument master

Trying to build a GUI in Python at the moment, and Im stuck at this part in particular. Every time I try to run my code it just throws the error TypeError: __init__() got multiple values for argument m…

How to suppress all warnings in window of executable file generated by pyinstaller

I have generated an executable file from a python file using pyinstaller. The program works how it is supposed to work but there is this warning message it appears in the window that I would like to hi…