HTTP Requests
HTTP Requests
requests. The most common types of HTTP requests are GET (retrieve data), POST
(send data), PUT (update data), and DELETE (remove data).
To make HTTP requests in Python, we can use the built-in requests module.
Making a GET Request 🧲
A GET request retrieves data from a web server. Here’s how you can make a GET
request to a sample API:
import requests
response = requests.get('https://jsonplaceholder.typicode.com/posts')
# Let's print the status code
print(response.status_code) # 200 means success!
# Now, let's print the data
print(response.json())
The response.json() method returns the data we received from the API in JSON
format.
Making a POST Request 📤
A POST request sends data to a web server. Here’s how you can make a POST request:
import requests
data = {
"title": "foo",
"body": "bar",
"userId": 1
}
response = requests.post('https://jsonplaceholder.typicode.com/posts', data=data)
# Print the status code
print(response.status_code) # 201 means created!
# Print the response data
print(response.json())
In this example, the data dictionary contains the data we want to send to the API.
Hang tight, coding comrades! 🖖 No need for exercise at this moment. We’ll get
plenty of hands-on practice interacting with APIs in our upcoming lectures.
So, rest up and brace yourselves for the exciting coding challenges that lie ahead!