Chapter 1.2: HTTP Methods and Status Codes
Study time: 40 minutes
1. HTTP: The Language of Communication in Space
Imagine you are the Mission Control Center (MCC), and the API server is a spaceship. HTTP (HyperText Transfer Protocol) is the radio communication between you.
Each message contains:
-
Method → What to do (e.g., "launch a probe")
-
Status code → Result of the operation ("probe launched successfully!")
💡 Space analogy:
GET /stars
= "MCC → Ship: Report star coordinates!"200 OK
= "Ship → MCC: Coordinates transmitted!"
2. Basic HTTP Methods
Each method is like a type of command for a space mission:
Method | Space Analogy | Example Request | Description |
---|---|---|---|
GET | Requesting data (telescope) | GET /planets |
Get a list of planets |
POST | Sending a new object (rocket launch) | POST /satellites |
Create a new satellite |
PUT | Full object update (orbit correction) | PUT /satellites/iss |
Update ISS data |
DELETE | Destroying an object (de-orbiting) | DELETE /debris/123 |
Delete space debris |
⚡ Code Example (Python):
import requests
# GET: Get data about the Falcon 9 rocket
# Using a real SpaceX API endpoint
response = requests.get("https://api.spacexdata.com/v4/rockets/5e9d0d95eda69973a809d1ec")
print(response.status_code, response.json()['name']) # 200 Falcon 9
# POST: Create a new post in a test API
# Using the jsonplaceholder sandbox service
new_post = {"title": "Artemis Mission", "body": "Ready for launch", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=new_post)
print(response.status_code, response.json()['id']) # 201 101 (or another ID)
3. Important Status Codes
The server's response is like a signal from a spacecraft:
Group | Code | Space Analogy | Description |
---|---|---|---|
2xx |
200 | ✅ "Mission accomplished!" | Success |
201 | 🚀 "Rocket launched!" | Object created | |
3xx |
301 | 🌍 "MCC has moved to a new address" | Redirection |
4xx |
400 | ❌ "Incorrect coordinates in the request!" | Client error |
404 | 🪐 "Planet not found!" | Resource not found | |
5xx |
500 | 🔥 "Engine failure!" | Server error |
4. Practice: Handling Status Codes
Always check the API response! Example of error handling:
import requests
def get_post_data(post_id):
"""Function to get post data with status code handling."""
try:
response = requests.get(f"https://jsonplaceholder.typicode.com/posts/{post_id}")
# Check the response status code
if response.status_code == 200:
print(f"✅ Data for post {post_id} successfully received!")
return response.json()
elif response.status_code == 404:
print(f"⚠️ Resource for post {post_id} not found!")
return None
else:
# Handle other client (4xx) or server (5xx) errors
print(f"🚨 An error occurred! Status code: {response.status_code}")
return None
except requests.exceptions.RequestException as e:
# Handle connection errors (e.g., no internet)
print(f"🔥 Connection error: {e}")
return None
# --- Testing our function ---
print("--- Searching for an existing post ---")
get_post_data(1)
print("\n--- Searching for a non-existent post ---")
get_post_data(9999) # This post does not exist, we expect a 404
🔭 Example from a real API (SpaceX): Request:
GET https://api.spacexdata.com/v4/ships/OCISLY
Response:200 OK
+ ship data Request:GET https://api.spacexdata.com/v4/ships/UNICORN
Response:404 Not Found
Quiz for reinforcement
🚀 Chapter summary: HTTP methods are your commands for space missions, and status codes are reports on their execution. Remember:
GET
= "Give me data",POST
= "Create new",PUT
= "Update all",DELETE
= "Destroy"2xx
= Success,4xx
= Your error,5xx
= Server problem
Get ready for launch! In the next chapter, we will decipher "telegrams" from the server - the JSON format.
📌 Practice: Use the SpaceX API to send
GET /launches/latest
and study the response codes!