Often the web framework that you use to implement the REST api will also offer unit testing support. For example:

  • Flask: http://flask.pocoo.org/docs/latest/testing/
  • Django: http://django-testing-docs.readthedocs.org/en/latest/views.html

These test classes are shortcuts which plug the request directly into the framework's Url dispatcher. That saves you the hassle of finding a free port, spawning a "real" server and connecting the http client from your unit test.

As for the e-mail sending: I would mock that part in the TestCase.setUp method. Just change the reference to the e-mail sending module / class to another module/class which loops the outgoing e-mail back to the unit test for evaluation rather than e-mailing.

Answer from Freek Wiekmeijer on Stack Overflow
🌐
LSEG
developers.lseg.com › home › article catalog › getting start with unit test for an http rest application with python
Getting Start With Unit Test for an HTTP REST Application with Python | Devportal
July 20, 2022 - The demo application uses a de-facto Requests library to connect to the Delivery Platform (RDP) APIs (formerly known as Refinitiv Data Platform)as the example HTTP REST APIs and uses the Python built-in unittest as a test framework.
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 ...")
🌐
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.
🌐
Readthedocs
http-api-base.readthedocs.io › en › latest › test
Writing tests - REST API automatic mock - Read the Docs
""" Test dataobjects endpoints """ import io import os import json import unittest from restapi.server import create_app __author__ = 'Roberto Mucci (r.mucci@cineca.it)' class TestDataObjects(unittest.TestCase): @classmethod def setUpClass(self): "set up test fixtures" print('### Setting up flask server ###') app = create_app() app.config['TESTING'] = True self.app = app.test_client() @classmethod def tearDownClass(self): "tear down test fixtures" print('### Tearing down the flask server ###') def test_01_get_verify(self): """ Test that the flask server is running and reachable""" r = self.app
🌐
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 - 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. This API takes a country code and a zip code and returns location data associated with that country and zip code.
🌐
Medium
medium.com › hackernoon › writing-unit-tests-for-rest-api-in-python-web-application-2e675a601a53
Writing Unit Tests for REST API in Python | by Parth Shandilya | HackerNoon.com | Medium
January 12, 2020 - To test this function, I basically ... the real REST API. Now the next challenge is to parse the JSON response and feed the specific value of the response JSON to the Python automation script. So Python reads the JSON as a dictionary object and it really simplifies the way JSON needs to be parsed and used. And here’s the content of the backend/tests/test_basic.py file. #!/usr/bin/env python3“””Tests for Basic Functions””” import sys import json import unittestsys.path.appe...
🌐
GitHub
github.com › LSEG-API-Samples › Article.RDP.Python.HTTP.UnitTest
GitHub - LSEG-API-Samples/Article.RDP.Python.HTTP.UnitTest: This is an example project that shows how to run unit test cases for a Python application that performs HTTP REST operations.
The demo application uses a de-facto Requests library to connect to the Delivery Platform (RDP) APIs (formerly known as Refinitiv Data Platform)as the example HTTP REST APIs and uses the Python built-in unittest as a test framework.
Author   LSEG-API-Samples
Find elsewhere
🌐
World Wide Technology
wwt.com › digital › software development › rest api integration testing using python
REST API Integration Testing Using Python - WWT
February 6, 2025 - All we need to do to get started is create a new Python file (we can create a new project in any IDE as well). import requests def test_get_employee_details_check_status_code_equals_200(): response = requests.get("http://demo.example.com/employee/employee1") assert response.status_code == 200 · What's happening here? We have imported the requests library to perform a REST API call.
🌐
My Developer Planet
mydeveloperplanet.com › 2020 › 03 › 11 › how-to-mock-a-rest-api-in-python
How to Mock a Rest API in Python - mydeveloperplanet.com
June 7, 2020 - import unittest class MyTestCase(unittest.TestCase): def test_something(self): self.assertEqual(True, False) if __name__ == '__main__': unittest.main() Running this unit test obviously fails (True does not equals False), but we do have set up the basics for writing our own unit tests now. We want to unit test the get_updated_issues function and this provides us a first challenge: the get_updated_issues function contains a call to the Jira Rest API.
🌐
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 import requests class IntegrationTests(TestCase): def test_header_invalid(self): result = requests.post( "http://localhost:5000/api/", headers = {'Content-Type': 'random/content'}, json = { "username": "fake", "password": "fakse", }, ) assert result.status_code == 415 assert result.headers.get("Content-Type") == "application/json" def test_header_correct(self): result = requests.post( "http://localhost:5000/api/", headers = {'Content-Type': 'application/json'}, json = { "username": "fake", "password": "fakse", }, ) assert result.status_code != 415
🌐
GitHub
github.com › chitamoor › Rester
GitHub - chitamoor/Rester: Testing RESTful APIs
docker run -v $(pwd)/rester/examples:/tests -it --rm --name rester raseev/rester apirunner --ts tests/imdb/test_suite.json --log=DEBUG ... Breaking change: __raw__ to raw on the TestStep. Feature: status to TestStep.asserts, allowing for non-200 replies. ... Use meta-programming to allow direct integration into unittest frameworks, and run with tests a la nose, to leverage all the things.
Starred by 85 users
Forked by 31 users
Languages   Python 100.0% | Python 100.0%
🌐
DZone
dzone.com › data engineering › databases › how to mock a rest api in python
How to Mock a Rest API in Python
April 16, 2020 - In this article, we discuss how to mock a REST API with request-mock and Python and perform unit tests.
🌐
Pytest With Eric
pytest-with-eric.com › pytest-best-practices › python-rest-api-unit-testing
Python REST API Unit Testing for External APIs | Pytest With Eric
November 18, 2022 - We use the RequestType enum class to handle each REST API Method Type e.g. GET, POST, PUT, PATCH, DELETE. Now that we’ve defined the Source Code let’s dive into the core idea. Python REST API unit testing for External APIs.
🌐
Codementor
codementor.io › community › writing unit tests for rest apis in python
Writing Unit Tests for REST APIs in Python | Codementor
February 14, 2018 - To test this function, I basically ... the real REST API. Now the next challenge is to parse the JSON response and feed the specific value of the response JSON to the Python automation script. So Python reads the JSON as a dictionary object and it really simplifies the way JSON needs to be parsed and used. And here’s the content of the backend/tests/test_basic.py file. #!/usr/bin/env python3 “””Tests for Basic Functions””” import sys import json import unittest ...
🌐
Miguendes
miguendes.me › 3-ways-to-test-api-client-applications-in-python
3 Ways to Unit Test REST APIs in Python
September 19, 2020 - Master REST API testing in Python. Learn how to test HTTP calls to an external API using VCR.py, pytest-mock and the responses / requests libraries.
🌐
HackerNoon
hackernoon.com › writing-unit-tests-for-rest-api-in-python-web-application-2e675a601a53
Writing Unit Tests for REST API in Python | HackerNoon
January 31, 2018 - A little background: over the last few months, I have been contributing in open source organization FOSSASIA, where I’m working on a project called BadgeYaY. It is a badge generator with a simple web UI to add data and generate printable badges in PDF.
🌐
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 - The Requests library is a powerful and user-friendly HTTP library for Python. It is designed to make HTTP requests simpler and more intuitive, so it is a good choice to use it for API testing.