Hypertext Transfer Protocol methods (aka HTTP Verbs) are actions that define the desired operation to be performed on a resource identified by a URI (Uniform Resource Identifier). These methods indicate what type of request is being made and how the server should process it. Most of the things we want our programs to do to the resources can be expressed with the acronym CRUD—creating, reading, updating and deleting. There is an HTTP Verb that represents every CRUD need:
1. GET for Read:
Purpose: Retrieve data from the server.
How it Works: When you use the GET method, you are asking the server to send you some data. It does not change anything on the server.
Example!
Scenario: You want to print the current date and time in Casablanca, Africa.
Endpoint: "http://worldtimeapi.org"
HTTP Method: GET (to retrieve data)
Example Code:
# Import the requests library
import requests
# Define the API endpoint for Casablanca, Africa
url = "http://worldtimeapi.org/api/timezone/Africa/Casablanca"
# Make a GET request to the API
response = requests.get(url)
# Parse the JSON response
data = response.json()
# Extract the current time
current_time = data['datetime']
# Print the current time
print(f"The current date and time in Casablanca, Africa is: {current_time}")
Sample Output:
The current date and time in Casablanca, Africa is: 2024-07-03T18:12:07.634485+01:00
** The date and time will differ when you run the code, because the API updates in real-time. The time is in 24-hour.
2. POST for Create:
Purpose: Send data to the server to create a new resource.
How it Works: When you use the POST method, you are sending data to the server to create something new. The server processes this data and creates the resource.
Example!
Scenario: You want to add a new grocery list to the server’s database.
# Import requests library
import requests
# Base URL for JSONPlaceholder
url = "https://jsonplaceholder.typicode.com/posts"
# Create grocery list that you want to post to the API
grocery_list= {
"apples": 6,
"yogourts": 3,
"oranges": 18
}
# Post request
post_response = requests.post(url, json=grocery_list)
# Parse the JSON response
result = post_response.json()
# Print result
print("POST Response:", result)
Sample Output:
POST Response: {'apples': 'red', 'bananas': 'yellow', 'oranges': 18, 'id': 101}
** Here, id is just a unique identifier of the action that we just did. We could use this code to modify our POST action later, if we wanted to.
3. PUT for Update:
Purpose: Update an existing resource or create a new one if it does not exist.
How it Works: When you use the PUT method, you are sending data to the server to update an existing resource. If the resource does not exist, it may create a new one.
Example!
Scenario: You want to update the id of the previous grocery list we made, and add 5 potatoes to the list.
# Import requests library
import requests
# Define the API endpoint
url = "https://jsonplaceholder.typicode.com/posts/1"
# Update the previous grocery list with 5 potatoes and change the id to 1
new_grocery_list = {
"apples": 6,
"yogurts": 3,
"oranges": 18,
"potatoes": 5,
"id": 1
}
# Make the PUT request
put_response = requests.put(url, json=new_grocery_list)
# Parse the JSON response
result = put_response.json()
# Print result
print("New grocery list:", result)
# Import requests library
import requests
# Define API endpoint
url = "https://jsonplaceholder.typicode.com/posts/1"
# Delete the grocery list that we made
delete_response = requests.delete(url)
# We won't need to parse a JSON response here because we are deleting the response, therefore, there's nothing to parse
# Print Status code; a code of 2XX indicates successful deletion
print("DELETE Response Status Code:", delete_response.status_code)
Sample Output:
DELETE Response Status Code: 200
HTTP Status Codes
When you make an API request, the server responds with a status code. Here are some of the common ones:
1XX (Informational): The request was received, and the server is continuing the process.
2XX (Successful): The request was successful.
200 OK: The request was successful.
201 Created: A resource was successfully created.
3XX (Redirection): Further action is needed to complete the request.
4XX (Client Error): There was an error with the request.
400 Bad Request: The server could not understand the request due to invalid syntax.
401 Unauthorized: The client must authenticate itself to get the request response.
404 Not Found: The server cannot find the requested resource.
5XX (Server Error): The server has encountered an error and could not complete the request.
500 Internal Server Error: Ther server has an error.
503 Service Unavailable: The server is not ready to handle the request.