HTTP Methods (GET, POST, PUT, DELETE)
π·οΈ APIs and HTTP Requests / API Architecture Brief Recap
π Introduction: Why HTTP Methods Matter
When you interact with any modern applicationβwhether it's checking the weather, uploading a file, or updating a server configurationβyou are using HTTP methods. These methods define the action you want to perform on a resource (like a user, a server, or a database record).
Think of HTTP methods as verbs in a conversation with a server: - GET = "Show me this data." - POST = "Create something new." - PUT = "Replace or update this data." - DELETE = "Remove this data."
For engineers working with APIs, automation scripts, or cloud infrastructure, understanding these four methods is essential. They form the backbone of how systems communicate.
βοΈ The Four Core HTTP Methods
π₯ GET β Retrieve Data
Purpose: Fetch or read data from a server. This is the most common HTTP method.
Key characteristics: - Safe β It does not change anything on the server. - Idempotent β Calling it multiple times returns the same result. - No request body β Data is sent via URL parameters or query strings.
Real-world example: Checking the status of a cloud server or listing all active virtual machines.
Python example (using the requests library): - Import the requests library. - Call requests.get("https://api.example.com/servers"). - The server responds with a list of servers in JSON format.
π€ POST β Create New Data
Purpose: Send data to the server to create a new resource.
Key characteristics: - Not safe β It modifies server state. - Not idempotent β Sending the same POST request twice creates two resources. - Has a request body β Data is sent in the body (usually as JSON).
Real-world example: Creating a new user account or provisioning a new virtual machine.
Python example: - Prepare a dictionary with the new server details (name, region, size). - Call requests.post("https://api.example.com/servers", json=server_data). - The server creates the resource and returns a confirmation with a new ID.
π PUT β Update or Replace Data
Purpose: Update an existing resource by replacing it entirely with new data.
Key characteristics: - Not safe β It modifies server state. - Idempotent β Sending the same PUT request multiple times results in the same final state. - Has a request body β You send the complete updated resource.
Real-world example: Updating the configuration of an existing server (e.g., changing its name or size).
Python example: - Prepare a dictionary with the updated server details (must include all fields). - Call requests.put("https://api.example.com/servers/123", json=updated_data). - The server replaces the existing resource with the new data.
ποΈ DELETE β Remove Data
Purpose: Delete a specific resource from the server.
Key characteristics: - Not safe β It modifies server state. - Idempotent β Deleting the same resource twice returns the same result (usually a success or "not found"). - Typically no request body β The resource is identified by its URL.
Real-world example: Terminating a cloud server or removing a user account.
Python example: - Call requests.delete("https://api.example.com/servers/123"). - The server deletes the resource and returns a success status (e.g., 204 No Content).
π Comparison Table: GET vs POST vs PUT vs DELETE
| Feature | GET | POST | PUT | DELETE |
|---|---|---|---|---|
| Action | Retrieve data | Create new data | Update/replace data | Remove data |
| Safe (read-only) | β Yes | β No | β No | β No |
| Idempotent | β Yes | β No | β Yes | β Yes |
| Has request body | β No | β Yes | β Yes | β Usually no |
| Common status codes | 200 OK | 201 Created | 200 OK / 204 No Content | 204 No Content / 404 Not Found |
| Example use case | List servers | Create a server | Update server config | Delete a server |
π οΈ How to Choose the Right Method
When writing automation scripts or building integrations, follow this simple decision tree:
- Do you just want to see data? β Use GET.
- Do you want to create something brand new? β Use POST.
- Do you want to update an existing thing completely? β Use PUT.
- Do you want to remove something? β Use DELETE.
Important note: Some APIs also use PATCH for partial updates (instead of PUT for full replacements). But for most infrastructure APIs, these four methods cover 90% of your needs.
π΅οΈ Common Pitfalls for Beginners
- Using GET to send sensitive data β Never send passwords or API keys in a GET request URL. Use POST with a body instead.
- Forgetting that PUT replaces everything β If you only send one field in a PUT request, the server may delete all other fields. Always send the complete resource.
- Not checking status codes β A 200 response doesn't always mean success. Always check the HTTP status code (200 = OK, 201 = Created, 204 = No Content, 404 = Not Found, 500 = Server Error).
- Assuming POST is idempotent β Sending the same POST twice often creates duplicate resources unless the API has built-in deduplication.
β Summary
| Method | When to Use | Python Function |
|---|---|---|
| GET | Read data | requests.get(url) |
| POST | Create new data | requests.post(url, json=data) |
| PUT | Replace existing data | requests.put(url, json=data) |
| DELETE | Remove data | requests.delete(url) |
Mastering these four HTTP methods gives you the power to interact with almost any API. Whether you're automating cloud infrastructure, monitoring system health, or building internal tools, these verbs are your universal language for talking to servers.
HTTP methods define the type of action a client wants to perform on a server resource.
π‘ Example 1: GET request to fetch data from a public API
This example shows the simplest GET request to retrieve information from a server.
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.status_code)
print(response.json()["title"])
π€ Output: 200
sunt aut facere repellat provident occaecati excepturi optio reprehenderit
π€ Example 2: POST request to create new data
This example sends new data to a server to create a resource.
import requests
new_post = {
"title": "My First Post",
"body": "This is the content of my post.",
"userId": 1
}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=new_post)
print(response.status_code)
print(response.json()["id"])
π€ Output: 201
101
π Example 3: PUT request to update existing data
This example replaces an entire resource with new data.
import requests
updated_post = {
"id": 1,
"title": "Updated Title",
"body": "This content has been completely replaced.",
"userId": 1
}
response = requests.put("https://jsonplaceholder.typicode.com/posts/1", json=updated_post)
print(response.status_code)
print(response.json()["title"])
π€ Output: 200
Updated Title
ποΈ Example 4: DELETE request to remove a resource
This example deletes a specific resource from the server.
import requests
response = requests.delete("https://jsonplaceholder.typicode.com/posts/1")
print(response.status_code)
print(response.text)
π€ Output: 200
{}
π§ͺ Example 5: Practical workflow using all four methods
This example demonstrates a complete cycle of creating, reading, updating, and deleting a resource.
import requests
base_url = "https://jsonplaceholder.typicode.com/posts"
# CREATE - POST
new_data = {"title": "Test", "body": "Testing workflow", "userId": 1}
create_response = requests.post(base_url, json=new_data)
new_id = create_response.json()["id"]
print("Created ID:", new_id)
# READ - GET
get_response = requests.get(f"{base_url}/{new_id}")
print("Read title:", get_response.json()["title"])
# UPDATE - PUT
update_data = {"id": new_id, "title": "Updated", "body": "Updated content", "userId": 1}
put_response = requests.put(f"{base_url}/{new_id}", json=update_data)
print("Updated title:", put_response.json()["title"])
# DELETE - DELETE
delete_response = requests.delete(f"{base_url}/{new_id}")
print("Deleted status:", delete_response.status_code)
π€ Output: Created ID: 101
Read title: Test
Updated title: Updated
Deleted status: 200
π HTTP Methods Comparison Table
| Method | Purpose | Idempotent | Body Required |
|---|---|---|---|
| GET | Retrieve data | Yes | No |
| POST | Create new data | No | Yes |
| PUT | Replace existing data | Yes | Yes |
| DELETE | Remove data | Yes | No |
π Introduction: Why HTTP Methods Matter
When you interact with any modern applicationβwhether it's checking the weather, uploading a file, or updating a server configurationβyou are using HTTP methods. These methods define the action you want to perform on a resource (like a user, a server, or a database record).
Think of HTTP methods as verbs in a conversation with a server: - GET = "Show me this data." - POST = "Create something new." - PUT = "Replace or update this data." - DELETE = "Remove this data."
For engineers working with APIs, automation scripts, or cloud infrastructure, understanding these four methods is essential. They form the backbone of how systems communicate.
βοΈ The Four Core HTTP Methods
π₯ GET β Retrieve Data
Purpose: Fetch or read data from a server. This is the most common HTTP method.
Key characteristics: - Safe β It does not change anything on the server. - Idempotent β Calling it multiple times returns the same result. - No request body β Data is sent via URL parameters or query strings.
Real-world example: Checking the status of a cloud server or listing all active virtual machines.
Python example (using the requests library): - Import the requests library. - Call requests.get("https://api.example.com/servers"). - The server responds with a list of servers in JSON format.
π€ POST β Create New Data
Purpose: Send data to the server to create a new resource.
Key characteristics: - Not safe β It modifies server state. - Not idempotent β Sending the same POST request twice creates two resources. - Has a request body β Data is sent in the body (usually as JSON).
Real-world example: Creating a new user account or provisioning a new virtual machine.
Python example: - Prepare a dictionary with the new server details (name, region, size). - Call requests.post("https://api.example.com/servers", json=server_data). - The server creates the resource and returns a confirmation with a new ID.
π PUT β Update or Replace Data
Purpose: Update an existing resource by replacing it entirely with new data.
Key characteristics: - Not safe β It modifies server state. - Idempotent β Sending the same PUT request multiple times results in the same final state. - Has a request body β You send the complete updated resource.
Real-world example: Updating the configuration of an existing server (e.g., changing its name or size).
Python example: - Prepare a dictionary with the updated server details (must include all fields). - Call requests.put("https://api.example.com/servers/123", json=updated_data). - The server replaces the existing resource with the new data.
ποΈ DELETE β Remove Data
Purpose: Delete a specific resource from the server.
Key characteristics: - Not safe β It modifies server state. - Idempotent β Deleting the same resource twice returns the same result (usually a success or "not found"). - Typically no request body β The resource is identified by its URL.
Real-world example: Terminating a cloud server or removing a user account.
Python example: - Call requests.delete("https://api.example.com/servers/123"). - The server deletes the resource and returns a success status (e.g., 204 No Content).
π Comparison Table: GET vs POST vs PUT vs DELETE
| Feature | GET | POST | PUT | DELETE |
|---|---|---|---|---|
| Action | Retrieve data | Create new data | Update/replace data | Remove data |
| Safe (read-only) | β Yes | β No | β No | β No |
| Idempotent | β Yes | β No | β Yes | β Yes |
| Has request body | β No | β Yes | β Yes | β Usually no |
| Common status codes | 200 OK | 201 Created | 200 OK / 204 No Content | 204 No Content / 404 Not Found |
| Example use case | List servers | Create a server | Update server config | Delete a server |
π οΈ How to Choose the Right Method
When writing automation scripts or building integrations, follow this simple decision tree:
- Do you just want to see data? β Use GET.
- Do you want to create something brand new? β Use POST.
- Do you want to update an existing thing completely? β Use PUT.
- Do you want to remove something? β Use DELETE.
Important note: Some APIs also use PATCH for partial updates (instead of PUT for full replacements). But for most infrastructure APIs, these four methods cover 90% of your needs.
π΅οΈ Common Pitfalls for Beginners
- Using GET to send sensitive data β Never send passwords or API keys in a GET request URL. Use POST with a body instead.
- Forgetting that PUT replaces everything β If you only send one field in a PUT request, the server may delete all other fields. Always send the complete resource.
- Not checking status codes β A 200 response doesn't always mean success. Always check the HTTP status code (200 = OK, 201 = Created, 204 = No Content, 404 = Not Found, 500 = Server Error).
- Assuming POST is idempotent β Sending the same POST twice often creates duplicate resources unless the API has built-in deduplication.
β Summary
| Method | When to Use | Python Function |
|---|---|---|
| GET | Read data | requests.get(url) |
| POST | Create new data | requests.post(url, json=data) |
| PUT | Replace existing data | requests.put(url, json=data) |
| DELETE | Remove data | requests.delete(url) |
Mastering these four HTTP methods gives you the power to interact with almost any API. Whether you're automating cloud infrastructure, monitoring system health, or building internal tools, these verbs are your universal language for talking to servers.
Interactive Views
You are currently in π All-in-One mode. Use the tabs at the top to switch to π Theory Only or π» Code Only views.
HTTP methods define the type of action a client wants to perform on a server resource.
π‘ Example 1: GET request to fetch data from a public API
This example shows the simplest GET request to retrieve information from a server.
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.status_code)
print(response.json()["title"])
π€ Output: 200
sunt aut facere repellat provident occaecati excepturi optio reprehenderit
π€ Example 2: POST request to create new data
This example sends new data to a server to create a resource.
import requests
new_post = {
"title": "My First Post",
"body": "This is the content of my post.",
"userId": 1
}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=new_post)
print(response.status_code)
print(response.json()["id"])
π€ Output: 201
101
π Example 3: PUT request to update existing data
This example replaces an entire resource with new data.
import requests
updated_post = {
"id": 1,
"title": "Updated Title",
"body": "This content has been completely replaced.",
"userId": 1
}
response = requests.put("https://jsonplaceholder.typicode.com/posts/1", json=updated_post)
print(response.status_code)
print(response.json()["title"])
π€ Output: 200
Updated Title
ποΈ Example 4: DELETE request to remove a resource
This example deletes a specific resource from the server.
import requests
response = requests.delete("https://jsonplaceholder.typicode.com/posts/1")
print(response.status_code)
print(response.text)
π€ Output: 200
{}
π§ͺ Example 5: Practical workflow using all four methods
This example demonstrates a complete cycle of creating, reading, updating, and deleting a resource.
import requests
base_url = "https://jsonplaceholder.typicode.com/posts"
# CREATE - POST
new_data = {"title": "Test", "body": "Testing workflow", "userId": 1}
create_response = requests.post(base_url, json=new_data)
new_id = create_response.json()["id"]
print("Created ID:", new_id)
# READ - GET
get_response = requests.get(f"{base_url}/{new_id}")
print("Read title:", get_response.json()["title"])
# UPDATE - PUT
update_data = {"id": new_id, "title": "Updated", "body": "Updated content", "userId": 1}
put_response = requests.put(f"{base_url}/{new_id}", json=update_data)
print("Updated title:", put_response.json()["title"])
# DELETE - DELETE
delete_response = requests.delete(f"{base_url}/{new_id}")
print("Deleted status:", delete_response.status_code)
π€ Output: Created ID: 101
Read title: Test
Updated title: Updated
Deleted status: 200
π HTTP Methods Comparison Table
| Method | Purpose | Idempotent | Body Required |
|---|---|---|---|
| GET | Retrieve data | Yes | No |
| POST | Create new data | No | Yes |
| PUT | Replace existing data | Yes | Yes |
| DELETE | Remove data | Yes | No |