How to Use Pytest for REST API Testing

HOME

pip install -U pytest
pip install pytest requests

import pytest
import requests

BASE_URL = "https://reqres.in/api"

def test_get_endpoint():
       response = requests.get(f"{BASE_URL}/users/2")
       assert response.status_code == 200
       assert response.json()["data"]["email"]   == "janet.weaver@reqres.in"
       assert response.json()["data"]["id"] == 2
       assert response.json()["data"]["first_name"] == "Janet"
       assert response.json()["data"]["last_name"] == "Weaver"

def test_post_endpoint():
       payload = {"name": "Vibha", "job": "CTO"}
       headers = {"x-api-key": "reqres-free-v1"}

       response = requests.post(f"{BASE_URL}/users", headers=headers, json=payload)

       print(response.status_code)
       print(response.text) 
       assert response.status_code == 201
       assert response.json()["name"] == "Vibha"

BASE_URL = "https://reqres.in/api"
response = requests.get(f"{BASE_URL}/users/2")
assert response.status_code == 200
assert response.json()["data"]["email"]   == "janet.weaver@reqres.in"
assert response.json()["data"]["id"] == 2
assert response.json()["data"]["first_name"] == "Janet"
assert response.json()["data"]["last_name"] == "Weaver"

payload = {"name": "Vibha", "job": "CTO"}
headers = {"x-api-key": "reqres-free-v1"}
response = requests.post(f"{BASE_URL}/users", headers=headers, json=payload)
print(response.status_code)
print(response.text) 
assert response.status_code == 201
assert response.json()["name"] == "Vibha"
pytest test_api.py

pytest test_api.py --html=report.html

Leave a comment