Sending a GET request

A GET request allows the requester (often called a client) to receive some information from a server. We can use a GET request to ask our server for some data in JSON format, which we can then use in the rest of the script.

Ensure your flask server is still running, then, open up a new Python file. Add the following content:

import requests

r = requests.get("http://127.0.0.1:5000")
data = r.json()

print(f"There are {data['people']} people. {data['cats']} of them have a cat, and {data['dogs']} of them have a dog")

In this example, we import the requests module and use it to send a GET request to our server using its get method.

Since our server returns JSON, we can use the json method to parse the result into a Python dictionary, which we call data.

This data dictionary is then available to be used as a regular Python dictionary, which is demonstrated by using its attributes in a call to print.

Run the example and you should see the following output:

> python3 demo/req.py 
There are 8 people. 5 of them have a cat, and 4 of them have a dog

From this, you can see that the content of our data dictionary on the server was transferred successfully to this new script.

So, we've seen that we can get data from a server into an arbitrary script easily using the requests module, but what about sending data from our script to the server?

Thankfully, requests allows us to do that too, using an HTTP POST request.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset