import requests
= requests.get("https://jsonplaceholder.typicode.com/posts/1")
response response
<Response [200]>
requests
)HTTP Method | requests Function |
Purpose | Response Codes (Typical Success) |
---|---|---|---|
GET | requests.get() |
Retrieve resource/data | 200 OK |
POST | requests.post() |
Create a new resource | 201 Created |
PUT | requests.put() |
Update existing resource | 200 OK |
DELETE | requests.delete() |
Delete resource | 200 OK , 204 No Content |
This structure provides a clear, practical way of interacting with RESTful APIs through Python.
import requests
= requests.get("https://jsonplaceholder.typicode.com/posts/1")
response response
<Response [200]>
response.json()
{'userId': 1,
'id': 1,
'title': 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
'body': 'quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto'}
import requests
= {
payload "title": "Hello World",
"body": "This is my first API request!",
"userId": 1
}
= requests.post(
response "https://jsonplaceholder.typicode.com/posts",
=payload
json )
if response.status_code == 201: # 201 Created
= response.json()
data print("Created:", data)
else:
print("Error:", response.status_code)
Created: {'title': 'Hello World', 'body': 'This is my first API request!', 'userId': 1, 'id': 101}
import requests
= {
updated_payload "title": "Updated Title",
"body": "Updated body content",
"userId": 1
}
= requests.put(
response "https://jsonplaceholder.typicode.com/posts/1",
=updated_payload
json )
if response.status_code == 200:
= response.json()
data print("Updated:", data)
else:
print("Error:", response.status_code)
Updated: {'title': 'Updated Title', 'body': 'Updated body content', 'userId': 1, 'id': 1}
import requests
= requests.delete("https://jsonplaceholder.typicode.com/posts/1")
response
if response.status_code == 200 or response.status_code == 204:
print("Deleted successfully.")
else:
print("Error:", response.status_code)
Deleted successfully.