Python Requests API Automation Examples
# GET Method
import requests
url = "[Link]
params = {"page":1, "limit":10}
headers = {
"Authorization":"Bearer token123",
"Accept":"application/json"
}
cookies = {"session_id":"abc123"}
response = [Link](
url=url,
params=params,
headers=headers,
cookies=cookies,
auth=("user","pass"),
timeout=5,
allow_redirects=True,
verify=True
)
# Assertions (What we test)
assert response.status_code == 200
assert "users" in [Link]
print([Link]())
# POST Method
import requests
url = "[Link]
headers = {
"Content-Type":"application/json",
"Authorization":"Bearer token123"
}
json_body = {
"name":"Krishna",
"age":28
}
cookies = {"session_id":"abc123"}
response = [Link](
url=url,
json=json_body,
headers=headers,
cookies=cookies,
files=None,
auth=("user","pass"),
timeout=5
)
# Assertions
assert response.status_code in [200,201]
assert [Link]()["name"] == "Krishna"
print([Link]())
# PUT Method
import requests
url = "[Link]
headers = {"Content-Type":"application/json"}
json_body = {
"name":"Krishna",
"age":30
}
response = [Link](
url=url,
json=json_body,
headers=headers,
cookies={"session_id":"abc123"},
auth=("user","pass"),
timeout=5
)
# Assertions
assert response.status_code == 200
print([Link]())
# PATCH Method
import requests
url = "[Link]
headers = {"Content-Type":"application/json"}
json_body = {
"age":31
}
response = [Link](
url=url,
json=json_body,
headers=headers,
cookies={"session_id":"abc123"},
auth=("user","pass"),
timeout=5
)
# Assertions
assert response.status_code == 200
print([Link]())
# DELETE Method
import requests
url = "[Link]
headers = {
"Authorization":"Bearer token123"
}
response = [Link](
url=url,
headers=headers,
cookies={"session_id":"abc123"},
auth=("user","pass"),
timeout=5
)
# Assertions
assert response.status_code in [200,204]
print("User deleted successfully")