DEV Community

Cover image for Automating your API tests using Python and Pytest

Automating your API tests using Python and Pytest

Alicia Marianne on November 12, 2023

Did you ever thought how you can tests your APIs using python? In the article we will learn how we can test our APIs using Python and the pytest fr...
Collapse
 
proteusiq profile image
Prayson Wilfred Daniel • Edited

Really good step by step introduction to testing with pytest.

I usually Mock external calls with Postman as I wish not to respect the service, which I don’t own, with my tests.

from os import environ
import requests

def make_request():

    base_url = environ.get("BASE_URL")
    params = {"api_key": environ.get("API_KEY"),}
    response = requests.get(url=base_url, params=params)

    return response

Enter fullscreen mode Exit fullscreen mode

Postman has a good section here on how to mock external API

We would then inject URL and keys from environment variables 😉 which enable us to change Mocked and Real in our CI/CD without changing our code.

So the actions that do unit tests, will have mocked values, and ones doing integration will have real.

Collapse
 
brentbrewington profile image
Brent Brewington • Edited

Really nice post! Always good to explain virtual environments while working with Python, and I like the straightforward pytest example you provide

Best practice with unit testing code that calls API's is to mock the API interface, so you don't have to ping an external service (idea of unit tests is to be able to run them very quickly with very little external dependencies, if any). Here's a great RealPython article that walks through how to do this mocking...and just a heads up this might get a little more advanced for some readers, but good to know it's out there!

realpython.com/testing-third-party...

^ heads up, that example uses "nosetest" library (extension of unittest) rather than "pytest"

Here's a great explanation of when it makes sense to actually call the external API in tests: pytest-with-eric.com/pytest-best-p...

Collapse
 
ldrscke profile image
Christian Ledermann

For mocking external API calls responses and HTTPretty are my favourite helpers

Collapse
 
m4rri4nne profile image
Alicia Marianne

Thanks! This article was focused more on integration tests than unit tests, I'll take a look at your recommendations.

Collapse
 
ldrscke profile image
Christian Ledermann

Have you heard of schemathesis, a tool that automates your API testing to catch crashes and spec violations? Built on top of the widely-used Hypothesis framework for property-based testing.

Also available as a service

Collapse
 
m4rri4nne profile image
Alicia Marianne

Nice! I'll take a look at this one, I've never heard before.

Collapse
 
ganeshpulsars profile image
Ganesh
pytest test.py --html-report=./report/report.html 
Enter fullscreen mode Exit fullscreen mode

this should be

pytest test.py --html=./report/report.html 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ganeshpulsars profile image
Ganesh

Python 3.9.7
Platform Windows-10-10.0.19045-SP0
Packages pytest: 7.4.3
pluggy: 1.0.0
Plugins html: 4.1.1
metadata: 3.0.0

The above is my environment and the --html-report=./report.html did not work in this environment.

BTW, Sorry I forgot to mention that your tutorial was excellent. Even though I have been using python for past twenty years, I understood and started using pytest only after reading this. Thanks for the simple and lucid tutorial

Collapse
 
m4rri4nne profile image
Alicia Marianne

How I used pytest-html-reporter library, the recommendation on the documentation is to run:

--html-report=./report/report.html

You can check here more about it:
github.com/prashanth-sams/pytest-h...

Collapse
 
navcheru profile image
Naveen • Edited

Somehow, I am getting errors if my response includes dates. For the time being, I am using --html=./report/report.html. I need to find an alternative way to see a good HTML report that can show results in a graphical manner.

Collapse
 
suamirochadev profile image
Suami Rocha

Omg, i'm a surprised with your article! Very nice job, congrats Alicia!

Collapse
 
lliw profile image
William Rodrigues

This article was incredible! Congrats on this series on showing how to test our code in different ways, you're awesome!

Collapse
 
phenriquesousa profile image
Pedro Henrique

Thanks for sharing, cousin <3

Collapse
 
cherryramatis profile image
Cherry Ramatis

Amazing how python is easy to work with and thanks for the didactics around the QA version of testing!

Collapse
 
clintonrocha98 profile image
Clinton Rocha

Great article, before reading this content I thought tests were something from another world, I'm looking forward to the next ones!

Collapse
 
m1guelsb profile image
Miguel Barbosa

Perfect as always! Can't wait for the front-end test tutorials 🥰

Collapse
 
aleexvmax profile image
ALEX | {{django.developer || python.developer}}

Oi Alícia!

Parabéns pelo conteúdo top!
Que ajude muita gente.

Collapse
 
navcheru profile image
Naveen

Awesome. Very good article. I started learning Python a couple of weeks back and this aids me in automating one of my applications.