🌐
DEV Community
dev.to › m4rri4nne › automating-your-api-tests-using-python-and-pytest-23cc
Automating your API tests using Python and Pytest - DEV Community
May 9, 2025 - This article is a tutorial of how you can start to write your automated tests for an API using python and pytest framework and how generate one report html. You can access the project used in this tutorial here.
🌐
Playwright
playwright.dev › api testing
API testing | Playwright Python
Playwright can be used to get access to the REST API of your application. Sometimes you may want to send requests to the server directly from Python without loading a page and running js code in it. A few examples where it may come in handy: Test your server API.
Discussions

Useful libraries for integration/api testing
asserting on HTTP responses If you dont want to use the built in assertions, there are modules like pyresttest and pyhttptest. Honestly using assertions with requests is going to be easier. I guess you are looking for something like RestAssured from Java but for Python. Python doesn't really embrace the same kind of API style that Java does, so you probably wont find many things like that in this space. You can always use stuff like json path libraries and xpath libraries on pypi to deal with body assertions if you want to use that. mocking Assuming you mean mocking external services rather than object mocking as that is generally aimed at unit testing. If you need to mock network requests at an integration level, I'd probably suggest using tooling such as testcontainers. That lets you spin up a container within Docker for whatever you want (it supports Kafka, Mockserver (HTTP), localstack (full AWS API) etc out of the box). You can also then make use of WireMock and the Python WireMock Admin API if you want something more involved (again, using test containers). Testcontainers will also let you run databases and other stuff programmatically too. Verifying OpenAPI That isn't really Python specific, and is not possible to fully automate from a black box perspective (since you cant really just infer what operations and payloads and headers are needed in a standard way from just observing a running REST API). You could avoid this by using something like APIFlask for Flask, or drf-spectacular for Django to create your OA3 specs from your code at runtime instead though. From an API level, you could alternatively consider using a transport like gRPC rather than a pure REST API, or use protobuf for your serialization format. That would enable you to write your payloads in protobuf files and distribute them to the end users so they can recreate the API clients/payloads on their side directly via protoc. That would reduce the need for such heavy documentation using OpenAPI 3 as you'd then be mostly just documenting the parameters on the generated code like any other library API. Ideas If you are doing acceptance testing, I'd probably suggest using behavioural-driven-development using a tool like behave rather than using pytest or unittest or nose directly. That way you can keep your test logic in readable feature requirements files. https://behave.readthedocs.io/en/stable/tutorial.html https://cucumber.io/ Pytest has a BDD plugin but last time I used it, it was overly clunky and awkward in comparison to behave. It felt like it didnt really capture the spirit of BDD features being more agnostic since there were a bunch of fairly common requirements that it didnt really fulfill for me. If you need something like awaitility in Java and do not want to just write a basic shim around threads or asyncio, there is this library too: https://pypi.org/project/busypie/ I leave with an unpopular opinion here: a lot of the testing frameworks in Python do not feel as developed as other languages which is unfortunate. For example, Java has full support for Cucumber rather than using a separately maintained API. Testcontainers is far more robust and customizable (esp. with respect to Kafka), higher level libraries like JooQ exist for expressing stuff like SQL with a DSL without needing to delegate to an ORM and hope that the ORM supports all the features of SQL that you need. You also have tools like awaitility, first class support for Wiremock and Mockserver, proper in memory databases for testing like H2 and Derby. Stuff like Restassured also exists. You also have tools like Skyscreamer JSON Assert, XML Assert, etc. Python does seem to lack in this regard, so you will likely find yourself having to write some common code in a library eventually to achieve some more bespoke common stuff you may need to do in tests. (Disclaimer, I work writing cloud Java and Python APIs and systems; I cant speak as well for other langs like C#, Ruby, PHP, Rust, Go, etc). More on reddit.com
🌐 r/Python
11
2
February 21, 2023
Writing a unit test for Python REST API function - Stack Overflow
I'm currently learning Python REST API (side project). I've been reading a lot of tutorials from RealPython, Python Requests documentation, etc. I found this post on how to write try/except properl... More on stackoverflow.com
🌐 stackoverflow.com
API testing for new project (new to APIs)
I would choose your language first, and then a testing toolkit second. REST-assured is cool, but if nobody’s a Java expert, there’s no reason to learn Java just to use it. I’ve done a LOT of API testing over the past 18 years or so, but never have done it with Postman. In my case, it’s always been a matter of developing test automation in whatever the language of choice is - Java, C#, Python. More on reddit.com
🌐 r/softwaretesting
26
16
May 18, 2023
Help with a python API test framework

Robot framework https://github.com/robotframework/robotframework

More on reddit.com
🌐 r/softwaretesting
9
4
May 22, 2020
🌐
Applitools
testautomationu.applitools.com › python-api-testing
API Testing in Python - Test Automation University - Applitools
Welcome to the Test Automation University course on building an API test automation framework with Python.
🌐
Opensource.com
opensource.com › article › 21 › 9 › unit-test-python
3 ways to test your API with Python | Opensource.com
September 22, 2021 - In this tutorial, you'll learn how to unit test code that performs HTTP requests. In other words, you'll see the art of API unit testing in Python.
🌐
Medium
laerciosantanna.medium.com › mastering-restful-api-testing-with-pytest-56d22460a9c4
RESTful API Testing with PyTest: A Complete Guide | by Laércio de Sant' Anna Filho | Medium
February 13, 2024 - To ensure these APIs work reliably, consistently, and securely under various conditions, automated testing is indispensable. Enter PyTest, a potent and flexible Python testing framework that simplifies the way you write and execute tests.
🌐
CodiLime
codilime.com › blog › software development › backend › testing apis with pytest: how to effectively use mocks in python
Testing APIs with PyTest: How to Effectively Use Mocks in Python
October 22, 2024 - In this article, we'll explore how to test APIs in Python using the popular PyTest library. We'll also demonstrate how to use mocking to simulate responses from external services.
🌐
CoderPad
coderpad.io › blog › development › how-to-test-python-rest-apis
How to Test Python REST APIs - CoderPad
June 5, 2023 - import unittest from unittest import TestCase from flask_api_5 import CustomFlaskAPI, PostOutput from flask import Flask, jsonify, request, views from marshmallow import Schema, fields, validate app = Flask(__name__) class PostOutput(Schema): answers = fields.Int( required=True, strict=True, # Must be a whole number validate=validate.Range(min=1), # Must be positive ) class CustomFlaskAPI(views.MethodView): def post(self): result = { "answers": request.json.get("children", 0) + 1, } errors = PostOutput().validate(result) if len(errors) != 0: # Errors instead of returning malformed data return
🌐
Reddit
reddit.com › r/python › useful libraries for integration/api testing
r/Python on Reddit: Useful libraries for integration/api testing
February 21, 2023 -

I'd like to enhance my integration/api testing, looking for useful libraries that do all sort of stuff like asserting on HTTP responses, mocking network requests, verifying OpenAPI or anything similar that can improve my DX. Appreciate your ideas

Top answer
1 of 3
5
asserting on HTTP responses If you dont want to use the built in assertions, there are modules like pyresttest and pyhttptest. Honestly using assertions with requests is going to be easier. I guess you are looking for something like RestAssured from Java but for Python. Python doesn't really embrace the same kind of API style that Java does, so you probably wont find many things like that in this space. You can always use stuff like json path libraries and xpath libraries on pypi to deal with body assertions if you want to use that. mocking Assuming you mean mocking external services rather than object mocking as that is generally aimed at unit testing. If you need to mock network requests at an integration level, I'd probably suggest using tooling such as testcontainers. That lets you spin up a container within Docker for whatever you want (it supports Kafka, Mockserver (HTTP), localstack (full AWS API) etc out of the box). You can also then make use of WireMock and the Python WireMock Admin API if you want something more involved (again, using test containers). Testcontainers will also let you run databases and other stuff programmatically too. Verifying OpenAPI That isn't really Python specific, and is not possible to fully automate from a black box perspective (since you cant really just infer what operations and payloads and headers are needed in a standard way from just observing a running REST API). You could avoid this by using something like APIFlask for Flask, or drf-spectacular for Django to create your OA3 specs from your code at runtime instead though. From an API level, you could alternatively consider using a transport like gRPC rather than a pure REST API, or use protobuf for your serialization format. That would enable you to write your payloads in protobuf files and distribute them to the end users so they can recreate the API clients/payloads on their side directly via protoc. That would reduce the need for such heavy documentation using OpenAPI 3 as you'd then be mostly just documenting the parameters on the generated code like any other library API. Ideas If you are doing acceptance testing, I'd probably suggest using behavioural-driven-development using a tool like behave rather than using pytest or unittest or nose directly. That way you can keep your test logic in readable feature requirements files. https://behave.readthedocs.io/en/stable/tutorial.html https://cucumber.io/ Pytest has a BDD plugin but last time I used it, it was overly clunky and awkward in comparison to behave. It felt like it didnt really capture the spirit of BDD features being more agnostic since there were a bunch of fairly common requirements that it didnt really fulfill for me. If you need something like awaitility in Java and do not want to just write a basic shim around threads or asyncio, there is this library too: https://pypi.org/project/busypie/ I leave with an unpopular opinion here: a lot of the testing frameworks in Python do not feel as developed as other languages which is unfortunate. For example, Java has full support for Cucumber rather than using a separately maintained API. Testcontainers is far more robust and customizable (esp. with respect to Kafka), higher level libraries like JooQ exist for expressing stuff like SQL with a DSL without needing to delegate to an ORM and hope that the ORM supports all the features of SQL that you need. You also have tools like awaitility, first class support for Wiremock and Mockserver, proper in memory databases for testing like H2 and Derby. Stuff like Restassured also exists. You also have tools like Skyscreamer JSON Assert, XML Assert, etc. Python does seem to lack in this regard, so you will likely find yourself having to write some common code in a library eventually to achieve some more bespoke common stuff you may need to do in tests. (Disclaimer, I work writing cloud Java and Python APIs and systems; I cant speak as well for other langs like C#, Ruby, PHP, Rust, Go, etc).
2 of 3
1
Pytest
Find elsewhere
🌐
Tavern
taverntesting.github.io
Easier API testing | Tavern
Tavern is a pytest plugin, command-line tool and Python library for automated testing of APIs, with a simple, concise and flexible YAML-based syntax. It’s very simple to get started, and highly customisable for complex tests.
🌐
GitHub
github.com › NAVEENINTEL › python-pytest-api-testing
GitHub - NAVEENINTEL/python-pytest-api-testing: Complete Automation framework for API using python + pytest +requests +github actions · GitHub
This project is a Python-based API automation framework for testing the reqres.in RESTful web service.
Starred by 16 users
Forked by 8 users
Languages   Python 98.9% | HTML 0.5% | PowerShell 0.2% | JavaScript 0.2% | CSS 0.1% | C 0.1%
🌐
Udemy
udemy.com › development
Learn API Automation Testing with Python & BDD Framework
4 weeks ago - Authenticating API's using Python Automation auth method- Example11:05 ... Section 4 and 5 Quiz - Test Your API Automation Knowledge!
Rating: 4.6 ​ - ​ 3.05K votes
🌐
GitHub
github.com › topics › api-testing-python
api-testing-python · GitHub Topics · GitHub
A Rest-API test automation framework which is build on the top of Python language using PyTest Framework.
🌐
Medium
medium.com › @vialyx › api-automation-testing-with-python-a-complete-guide-ce221604ab85
API Automation Testing with Python: A Complete Guide | by Maksim Vialykh | Medium
May 8, 2025 - def test_unauthorized_request(): response = requests.get(API_URL) assert response.status_code == 401 · You can manage tokens using .env files and python-dotenv.
Top answer
1 of 3
5

There are several unit test frameworks available in Python. Try/except blocks are good for error handling, but you still need a separate unit test around the call if you want to unit test it.

You do have something you can test, you can just return it and test that in your unit test.

Example Unit test using unittest:

import unittest
import requests

class RestCalls():

    def google_do_something(blahblah):
        url= blahblah
        try:
            r = requests.get(url,timeout=1)
            r.raise_for_status()
            return r.status_code
        except requests.exceptions.Timeout as errt:
            print (errt)
            raise
        except requests.exceptions.HTTPError as errh:
            print (errh)
            raise
        except requests.exceptions.ConnectionError as errc:
            print (errc)
            raise
        except requests.exceptions.RequestException as err:
            print (err)
            raise


class TestRESTMethods(unittest.TestCase):

    def test_valid_url(self):
        self.assertEqual(200,RestCalls.google_do_something('http://www.google.com/search'))

    def test_exception(self):
        self.assertRaises(requests.exceptions.Timeout,RestCalls.google_do_something,'http://localhost:28989')

if __name__ == '__main__':
    unittest.main()

Executing should show (made some edits to this post, updated output included at bottom of post):

> python .\Tests.py
 .
----------------------------------------------------------------------
Ran 1 test in 0.192s

OK

If you asserted a different response code from your request, it would fail (the request is just returning http response codes):

python .\Tests.py
F
======================================================================
FAIL: test_upper (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File ".\Tests.py", line 25, in test_upper
    self.assertEqual(404,RestCalls.google_do_something('search'))
AssertionError: 404 != 200

----------------------------------------------------------------------
Ran 1 test in 0.245s

FAILED (failures=1)

Which is expected.

Edit: Included exception testing. You can test these by just including raise in the except block, which will show this after running:

> python .\Tests.py
HTTPConnectionPool(host='localhost', port=28989): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x03688598>, 'Connection to localhost timed out. (connect timeout=1)'))
..
----------------------------------------------------------------------
Ran 2 tests in 2.216s

OK

References:

  • Unit tests in Python
  • https://docs.python.org/3/library/unittest.html
  • https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
2 of 3
2

I am not sure that your approach is such a good idea (just printing something in case of an error) but you could mock the print function to see if it was really called (and with what arguments):

https://docs.python.org/3/library/unittest.mock.html?highlight=mock#module-unittest.mock

Edit:

Working with mocks is a bit tricky as far as I remember. You would have to mock the print function in the current module. Perhaps something like this (not tested ...):

from unittest.mock import patch
from unittest import TestCase

class TestGoogleDoSomething(TestCase)
    
    @patch("nameOfYourModule.print")
    def test_google_do_something(self, print_mock): # the decorator will pass the mock object into the function
        g = google_do_something('blahblah')
        print_mock.assert_called_with("your error message here ...")
🌐
On Test Automation
ontestautomation.com › writing-tests-for-restful-apis-in-python-using-requests-part-1-basic-tests
Writing tests for RESTful APIs in Python using requests – part 1: basic tests | On Test Automation
December 12, 2019 - I prefer pytest, but requests works equally well with other Python unit testing frameworks. ... Then, all we need to do to get started is to create a new Python file and import the requests library using ... Our API under test For the examples in this blog post, I’ll be using the Zippopotam.us REST API.
🌐
NashTech Blog
blog.nashtechglobal.com › home › api testing with pytest and python requests: a beginner’s guide
API Testing with Pytest and Python Requests: A Beginner’s Guide - NashTech Blog
December 5, 2024 - Pytest is a one of the most robust testing framework which supports us to implement and manage test case easily in Python. By using Pytest, we can: ... Requests library is the most popular library which can be used for calling Rest API.
🌐
Testsprite
testsprite.com › use-cases › en › the-best-python-api-testing-tools
Ultimate Guide - The Best Python API Testing Tools of 2026
Ultimate Guide – The Best Python API Testing Tools of 2026: TestSprite, Pytest, Unittest, Robot Framework, and Apidog. Compare features for REST/GraphQL, CI/CD integration, fixtures, mocks, and autonomous testing. Find the best tool for fast, reliable Python API validation in 2026.
🌐
Isha
ishatrainingsolutions.org › home › courses › 4. other testing courses
API Testing with Python : Frameworks, CI/CD, and Automation | Isha
November 26, 2025 - This API Testing with Python course provides a comprehensive understanding of API automation using Postman and Python Requests. It covers essential topics like REST API methods, JSON & XML validation, authentication techniques, and Chai assertions.
🌐
GeeksforGeeks
geeksforgeeks.org › python › create-api-tester-using-python-requests-module
Create API Tester using Python Requests Module - GeeksforGeeks
July 23, 2025 - In this article, we will discuss the work process of the Python Requests module by creating an API tester.
🌐
Udemy
udemy.com › it & software
API Testing with Python 3 & PyTest, Backend Automation 2026
January 20, 2026 - Course Description Learn how to use Python to test the back-end of web services or APIs. We use industry-standard real eCommerce RESTful API to practice testing using Python programming language.
Rating: 4.5 ​ - ​ 1.93K votes