Python API Testing Complete Guide | pytest × requests from CRUD Tests to HTML Reports and CSV Output

test-automation

For engineers who want to start API testing with Python. From CRUD API testing with pytest and requests to HTML reports and CSV output — you can learn it all in this one series.

This article provides a complete overview of every article in the API testing series. It’s designed for step-by-step learning from beginners to working engineers.

Conclusion

If you want to automate API testing with Python, the pytest + requests combination is the simplest and most widely used approach in real-world projects.

This series is structured so you can learn the following systematically across 7 articles.

  • Fundamentals of API testing
  • CRUD operation implementation (GET, POST, PUT/PATCH, DELETE)
  • Production patterns: header validation, schema validation, and more
  • Visualizing results with HTML reports (pytest-html)
  • Recording and sharing test results with CSV evidence

📌 Who This Article Is For

  • Those who want to learn API testing with Python from scratch
  • Those who want a consolidated reference for pytest and requests usage
  • Those who want to add full CRUD API testing to their portfolio
  • Those who want to become engineers who can handle both UI and API testing

What You Will Learn in This Series

  • What API testing is and why it matters
  • Full test implementation for GET, POST, PUT/PATCH, and DELETE with pytest and requests
  • Production patterns: raise_for_status(), header validation, schema validation
  • Visualizing and sharing test results with HTML reports and CSV output

👨‍💻 About the Author

Working as a QA engineer handling API test automation with Python, pytest, and requests in real-world projects. All code used in this series is publicly available on GitHub and has been verified to work as described. View code on GitHub →


00. About This API Testing Series

This series consists of 7 articles designed to teach you API testing with Python from zero. Starting from environment setup, you’ll implement all CRUD operations step by step — and by the end, you’ll know how to manage and share test results with HTML reports and CSV files.

ArticleTitleContent
What Is API Testing?Concepts, differences from UI testing, basic patterns
Environment Setuppip install, venv, pytest.ini configuration
GET TestsStatus, response, schema validation
POST TestsData creation, ID assignment, validation testing
PUT/PATCH TestsFull vs partial update differences and implementation
DELETE TestsDeletion and post-deletion 404 verification
CSV Output & Reportingpytest-html, CSV output, evidence management

💡 Key Takeaway:Each article can be read independently, but reading in order ①→②→③ gives you the most systematic learning experience. If you only need a specific HTTP method, feel free to jump directly to that article.


01. API Testing Series — Article List

Each article can be read independently, but reading in order ①→②→③ is recommended for systematic learning.

📘
① What Is API Testing? — Intro

Core concepts of API testing, differences from UI testing, and basic patterns with requests and pytest

→ Read Article

🛠️
② Environment Setup Guide

pip install, venv, pytest.ini configuration, and running a verification test

→ Read Article

🔍
③ GET Tests

Status, response, header, and schema validation (9 test cases)

→ Read Article

✏️
④ POST Tests

Data creation, ID assignment, and validation error testing (9 test cases)

→ Read Article

🔄
⑤ PUT/PATCH Tests

Full vs partial update differences and implementation (9 test cases)

→ Read Article

🗑️
⑥ DELETE Tests

Deletion, post-deletion 404 verification, and 204 handling (7 test cases)

→ Read Article

📊
⑦ CSV Output & HTML Report

pytest-html, CSV append mode, utf-8-sig, fixture initialization, response.elapsed

→ Read Article


02. Production Code Patterns Learned in This Series

Here is a summary of the code patterns that appear consistently throughout this series — the ones you’ll use in every real-world project.

① The Production Baseline (3 lines used every time)

response = requests.get(url, timeout=5)
response.raise_for_status()  # Auto-exception on 4xx/5xx
elapsed_ms = response.elapsed.total_seconds() * 1000

② Header Check (partial match is correct)

# ✅ Use "in" for partial match — works even with charset appended
content_type = response.headers.get("Content-Type", "")
assert "application/json" in content_type

③ Batch Verification of Required Fields

required_fields = ["id", "name", "email"]
for field in required_fields:
    assert field in body, f"Required field '{field}' is missing"

④ Schema (Type) Validation

assert isinstance(body["id"],    int)
assert isinstance(body["name"],  str)
assert isinstance(body["email"], str)

⑤ Writing to CSV on Both PASS and FAIL

try:
    assert response.status_code == 200
    write_result("TC01", "GET /users/1", "PASS", ...)
except AssertionError as e:
    write_result("TC01", "GET /users/1", "FAIL", ..., str(e))
    raise  # Tell pytest the test failed

💡 Key Takeaway:Combining these 5 patterns is all you need to write production-level API test code.


03. Complete List of Test Cases Implemented in This Series

Across the entire series, we implemented a total of 34 test cases.

CategoryCountKey Verifications
GET Tests9Status, raise_for_status, header, body, fields, schema, 404, list, response time
POST Tests9201 check, raise_for_status, header, body, ID assignment, missing fields, empty string, invalid email, schema
PUT/PATCH Tests9PUT 200, raise_for_status, PUT body, header, PATCH 200, PATCH body, PATCH multiple fields, schema, 404
DELETE Tests7200 check, raise_for_status, response body, post-deletion 404, non-existent resource, 200/204, header

💡 Key Takeaway:34 test cases covers all CRUD operations. This is more than enough to demonstrate “I can write API tests” in a portfolio.


04. How to Use This Series in Your Portfolio

Here are key tips for publishing the code from this series as a portfolio.

Recommended GitHub Structure

automated-testing-portfolio/
├── README.md              ← List of test cases and how to run them
├── pytest.ini             ← HTML report auto-generation config
├── requirements.txt       ← Dependency library list
├── tests/
│   ├── test_get_api.py    ← GET tests (9 cases)
│   ├── test_post_api.py   ← POST tests (9 cases)
│   ├── test_put_patch_api.py ← PUT/PATCH tests (9 cases)
│   └── test_delete_api.py ← DELETE tests (7 cases)
├── report.html            ← Test run results (HTML report)
└── test_results.csv       ← Test run results (CSV)

💡 Key Takeaway:Including report.html and test_results.csv in your GitHub repository gives anyone who visits immediate proof that you actually ran the tests. This is a powerful signal to clients and hiring managers.


05. Series-Wide Pitfalls & Lessons Learned

Here is a summary of the most commonly encountered pitfalls across the entire series.


① Use “in” not “==” for Content-Type

# ❌ Fails when charset is appended
assert response.headers["Content-Type"] == "application/json"

# ✅ Partial match is safe
assert "application/json" in response.headers.get("Content-Type", "")

② Calling json() on 204 No Content raises an error

# ✅ Branch on status code
if response.status_code == 204:
    body = None
else:
    body = response.json()

③ Knowing when to use raise_for_status vs assert

# Positive case: use raise_for_status() to catch all 4xx/5xx at once
response.raise_for_status()

# Negative case: use assert when intentionally verifying a 4xx/5xx response
response = requests.delete(url, timeout=5)
assert response.status_code == 404

④ Use utf-8-sig for CSV files to support Excel

# ✅ No garbled text when opening in Excel
with open(CSV_FILE, mode="w", encoding="utf-8-sig") as f:
    ...

⑤ Use timeout and response.elapsed for production quality

# ✅ Production baseline pattern
response = requests.get(url, timeout=5)
elapsed_ms = response.elapsed.total_seconds() * 1000

06. Frequently Asked Questions (FAQ)

Q. Should I use pytest or Postman for API testing?
A. Postman is great for manual testing and quick verification, but for automated testing and CI/CD integration, pytest + requests is the better choice. Managing tests as code allows for reuse, automated execution, and sharing on GitHub. For portfolio purposes, pytest + requests is strongly recommended.

Q. What order should I read this series in?
A. If you’re new to API testing, start with ①→②→③. If you only need a specific HTTP method, you can jump directly to that article — each one is written to be readable independently.

Q. Can I try these tests with APIs other than JSONPlaceholder?
A. Yes. Use Restful Booker for authentication flow testing, or reqres.in and your own API for more advanced scenarios. The code in this series can be applied to any API by simply changing the URL.

Q. Can I use the code from this series in my portfolio?
A. Absolutely. Publish it on GitHub and use it as your portfolio. Adding a test case list and run instructions to your README, along with the HTML report, will significantly boost the quality of your presentation.

Q. Should I include Playwright code in the same repository?
A. Yes. Publishing UI tests (Playwright) and API tests (requests) together in one repository lets you say “I can handle both UI and API testing.” This is the recommended structure for a portfolio on GitHub.

Q. Is there a way to integrate this into CI/CD?
A. Yes. Using GitHub Actions, you can automatically run your API tests on every push. Just create a .github/workflows/test.yml file with a step that runs the pytest command. This is a great next step after completing this series.


07. Summary

Automating API testing with Python is achievable at a production level by simply combining pytest and requests. The skills you’ve learned in this series are strong enough to use as a portfolio and as an appeal to clients on Upwork and LinkedIn.

This series covered everything from the basics of API testing to production patterns and report generation across 7 articles.

SkillContent
API Testing FundamentalsConcepts, environment setup, basic pattern understanding
Full CRUD Test ImplementationGET, POST, PUT/PATCH, DELETE (34 test cases)
Production Patternsraise_for_status, header validation, schema validation
Reporting & CSV Outputpytest-html, csv module, evidence management
Portfolio ApplicationGitHub publishing, HTML report, requirements.txt

Thank you for reading this series all the way through. Go ahead and put these skills to work in your portfolio as an engineer who can say: “I do both UI testing and API testing.” 💪

⬅️ Previous Article

How to Output Python API Test Results to CSV & HTML Report | pytest × requests

Read Article →

📚 Series Index

Python API Testing Complete Guide | pytest × requests from CRUD Tests to HTML Reports and CSV Output

View Index →

Copied title and URL