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
Answer from user176692 on Stack Overflow
🌐
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.
🌐
Real Python
realpython.com › api-integration-in-python
Python and REST APIs: Interacting With Web Services – Real Python
December 6, 2023 - GET is one of the most common HTTP methods you’ll use when working with REST APIs. This method allows you to retrieve resources from a given API. GET is a read-only operation, so you shouldn’t use it to modify an existing resource. To test out GET and the other methods in this section, you’ll use a service called JSONPlaceholder. This free service provides fake API endpoints that send back responses that requests can process. To try this out, start up the Python REPL and run the following commands to send a GET request to a JSONPlaceholder endpoint:
Discussions

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 a python project

pytest is an excellent choice.

More on reddit.com
🌐 r/learnpython
7
1
January 28, 2019
Build RESTful API in Python.

Flask with the REST add-on is a good choice for a small, quick project.

  • Flask

  • Flask-RESTful

More on reddit.com
🌐 r/Python
24
10
March 9, 2016
Simple tutorials for using reddit api in Python?

Using an API just comes down to making a request to the right end-point (e.g. /api/v1/me), which then returns data. Most of the time this data is in either JSON or XML format.

Now in order to view that end-point (/api/v1/me) you need to be authenticated via OAuth, which is a whole separate process. (But also including making requests by sending the right data back and forth.)

Now to make it easy, you can just use PRAW. Which has a small tutorial on their website. :)

More on reddit.com
🌐 r/learnpython
31
31
May 21, 2015
🌐
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
🌐
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 - ============================= test session starts ============================== collecting ... collected 7 items test.py::TestClass::test_search_asteroids_with_sucess test.py::TestClass::test_search_asteroids_with_query_parameters_empty test.py::TestClass::test_search_asteroids_with_start_date test.py::TestClass::test_search_asteroids_with_end_date test.py::TestClass::test_search_asteroids_in_valid_range test.py::TestClass::test_search_asteroids_in_invalid_range test.py::TestClass::test_search_asteroids_in_invalid_token ============================== 7 passed in 5.85s ========================
🌐
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 - Master the art of testing RESTful APIs using PyTest. Learn essential techniques, best practices, and how to automate your API testing for robust applications.
🌐
Medium
lahiruprabodha.medium.com › rest-api-integration-testing-with-pythonrest-api-integration-testing-with-python-25116569e1b2
REST API Integration Testing with Python | by Lahiru Prabodha | Medium
December 20, 2022 - In the case of REST API integration testing with Python, you can use the Python requests library to send HTTP requests to the API endpoints and verify the response received. ... import requests # Set the API endpoint URL url = 'https://api....
🌐
LinkedIn
linkedin.com › pulse › api-test-automation-playwright-python-simplifying-palihawadana
API Test Automation with Playwright and Python: Simplifying API Testing
July 15, 2023 - In this article, we will explore how to perform REST API test automation using the powerful combination of Playwright and Python. We will provide very simple practical examples of test cases for common HTTP methods: POST and GET.
Find elsewhere
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 ...")
🌐
GitHub
github.com › krother › rest-test-tutorial
GitHub - krother/rest-test-tutorial: Tutorial for writing tests for a REST API in Python
In this tutorial, you learn to write tests for a Python REST API powered by a database. You will use the pytest framework to create Unit Tests, Integration Tests and end-to-end tests.
Author   krother
🌐
Playwright
playwright.dev › api testing
API testing | Playwright Python
The following examples rely on the pytest-playwright package which add Playwright fixtures to the Pytest test-runner. APIRequestContext can send all kinds of HTTP(S) requests over network.
🌐
Medium
elixirautomation.medium.com › automated-api-testing-playwright-part-1-d8eea1ccf0aa
Demystifying API Testing: A Comprehensive Guide with Playwright and Python (Part 1)
October 19, 2023 - 🍀 Always add “test” prefix or suffix to your python file & test method names so that pytest can easily catch your scripts for test execution. ... import pytest from typing import Generator from playwright.sync_api import Playwright, APIRequestContext
🌐
Splunk Community
community.splunk.com › t5 › Splunk-Dev › REST-API-Python-example › m-p › 160961
Solved: REST API Python example - Splunk Community
September 28, 2020 - http://docs.splunk.com/Documentation/Splunk/6.1/RESTAPI/RESTsearches I am testing out this script and it works with a few modifications on the endpoints I changed. /services/search/jobs','POST' I changed the endpoint to: /services/search/jobs/%s/results' % (sid),'GET' My results are great, ...
🌐
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 - With unit testing, developers can verify if their code can connect and consume content via HTTP REST API in any code updates. 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.
🌐
GitConnected
levelup.gitconnected.com › rest-api-test-automation-using-python-with-tavern-ci-part-1-707026eae702
REST-API test automation using Python with tavern-ci — Part 1 | by Imran Ali | Level Up Coding
November 3, 2020 - In most cases Python code will only be required to validate the response which is not simple enough to be verified by the tavern-ci framework. Enough talk! Lets see some examples starting from simple tests in this part building up to complicated tests in upcoming parts. I will be using the free public REST API at http://www.tvmaze.com/api for the examples.
🌐
Semaphore
semaphoreci.com › home › building and testing an api wrapper in python
Building and Testing an API Wrapper in Python - Semaphore
April 23, 2021 - Now that we’ve implemented an API wrapper, let’s check if it works by using it in a script. To do this, we will write a program that lists out all the popular TV shows on TMDb along with their popularity rankings. Create a file in the root folder of our project. You can name the file anything you like — ours is called testrun.py. # example.py from __future__ import print_function from tmdbwrapper import TV popular = TV.popular() for number, show in enumerate(popular['results'], start=1): print("{num}. {name} - {pop}".format(num=number, name=show['name'], pop=show['popularity']))
🌐
Automationqahub
automationqahub.com › home › api testing › how to do api testing using python requests
How To Do API Testing Using Python Requests
April 23, 2024 - With the above method, I have created a dictionary payload containing updated user data, including a modified job value and sent the put request to update the user details for the user with ID 2, using the provided payload. Once the put method is successful, the next step is to assert whether the job is updated or not. In the above code, I have added 3 assert statements to check the updated response. Many APIs require authentication to access protected resources. Python Requests supports various authentication methods, including basic authentication, API keys, OAuth, and more. For example, to authenticate using an API key, you can include it in the request headers:
🌐
FastAPI
fastapi.tiangolo.com
FastAPI
You will see the automatic interactive API documentation (provided by Swagger UI): And now, go to http://127.0.0.1:8000/redoc. You will see the alternative automatic documentation (provided by ReDoc): Now modify the file main.py to receive a ...