Fetching data from the client side of your web application is a crucial part of creating dynamic, modern web pages. That doesn't mean it's the only option developers have for sending HTTP requests via their apps. This post will explain how and why to use the requests library for Python in order to make server side HTTP requests.
There are a lot of good reasons to make requests from the backend. Perhaps you're using an external API and you don't want to accidentally reveal your API key in the frontend traffic. Maybe you want to avoid the CORS issues that arise when you task the browser with reaching out to some APIs. Whatever the reason, making requests using Python is an important tool to have in your kit.
Start by installing the requests library for Python in the virtual environment where you are working:
pipenv install requests
Inside of your Python file make sure to import the requests library:
import requests
Using the library is pretty straightforward. Making a get request and printing the response body look like this:
import requests
# Sample url, try it out with your own endpoints!
url = "http://127.0.0.1:5555/api/cars"
response = requests.get(url)
print(response.text)
Note that requests
has a get
method which takes the url string as its argument. It returns a response object. This is a powerful object with lots of functionalities built right in. It can provide the response body in text or JSON format. It can also tell you about the status code, headers, the time elapsed during the request, and more. This resource goes into more detail about the response object and its methods. In the example above, response.text
provides an easy-to-read, formatted version of the JSON data in the response. If you have more programatic work to do with the response, such as parsing through it to access just the information you'll need, then consider using the response.json()
method.
The requests library can perform the usual types of HTTP requests. The main differences between making a GET request and a POST request are just what you'd expect: you need to specify post as the method and provide a body for the request:
import requests
url = "http://127.0.0.1:5555/api/pieces"
body = {
"name": "example",
"description": "Words describing the thing",
"image_url": "image url here"
}
resp = requests.post(url, json=body)
print(resp.text)
Just like with a GET request, requests.post
returns a request object with all the same methods and attributes. Methods like PATCH and DELETE are similarly straightforward and will look familiar to anyone who has made requests using those methods from the frontend. Don't forget to check out the library's documentation for even more information on this useful tool!