How to run Python Rest API tests with GitHub Actions

Last Updated On

HOME

This tutorial explains the steps to create a GitHub Action for the Rest API tests built in Python and execute the tests in that workflow.

Table of Contents

Why GitHub?

Implementation Steps

Step 1 – Create GitHub Actions and Workflows

I have a repository available in GitHub – RestAPITesting_Python as shown in the below image. Go to the “Actions” tab.  Click on the “Actions” tab.

Step 2 – Select the type of Actions

You will see that GitHub recommends Actions depending on the project. In our case, it is recommending actions suitable for a Python project. I have selected the “Python application” option.

Step 3 – Generation of Sample pipeline

If you choose an existing option, it will automatically generate a .yaml for the project as shown below.

We will replace the current workflow with the following yml file as shown below:

# This workflow will install Python dependencies, run tests and lint with a single version of Python
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python

name: Python application

on:
  push:
    branches: [ "main" ]
  pull_request:
    branches: [ "main" ]

permissions:
  contents: read

jobs:
  build:

    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3
    - name: Set up Python 3.12.1
      uses: actions/setup-python@v3
      with:
        python-version: "3.12.1"
   
    - name: Install dependencies
      run: |
        python -m pip install --upgrade pip
        pip install pytest
        pip install requests
       
    - name: Test with pytest
      run: |
        cd TestCases
        pytest  --verbose --capture=no

Step 4 – Commit the changes

After the changes, hit the “Start Commit” button.

This will give the option to add a description for the commit. It will also enable the user to commit either to the main branch or commit to any other branch that exists in the project. Click on the “Commit new file” button to set up the workflow file.

Step 5 – Verify that the workflow is running

Next, head over to the “Actions” tab, and you will see your YAML workflow file present under the tab. The yellow sign represents that the job is in the queue.

In Progress – When the job starts building and running, you will see the status change from “Queued” to “in progress”.

Passed – If the build is successful, you will see a green tick mark. 

Click on the workflow and the below screen is displayed. It shows the status of the run of the workflow, the total time taken to run the workflow, and the name of the .yml file.

Below shows all the steps of the workflow.

The complete code can be found here on GitHub – vibssingh/RestAPITesting_Python.

Congratulations! We just created our CI workflow for running our Rest API test cases for Python.

How to pass basic authentication token in Python Requests

HOME

 headers = {'Authorization': 'Basic dXNlcjpwYXNz'}

import requests

endpoint = 'https://httpbin.org/basic-auth/user/pass'
token = 'Basic dXNlcjpwYXNz'


def test_auth_token():

    headers = {'Authorization': token}

    response = requests.get(endpoint, headers=headers)
    response_body = response.json()
    print(response_body)
    assert response.status_code == 200
    assert response_body["authenticated"] == True
    assert response_body["user"] == "user"

pytest Authentication_test.py -s

How to pass basic authentication credentials in Python Requests

HOME

response = requests.get(endpoint, auth=(username, password))

import requests

endpoint = 'https://httpbin.org/basic-auth/user/pass'
credentials = ('user', 'pass')


def test_basic_auth():

    response = requests.get(endpoint, auth=credentials)
    response_body = response.json()
    print(response_body)
    assert response.status_code == 200
    assert response_body["authenticated"] == True
    assert response_body["user"] == "user"

pytest BasicAuth_test.py -s

How to test response time in Request using Python Requests

HOME

import requests

endpoint = 'https://reqres.in/api/users'


def test_response():
    payload = {
        "name": "Vibha",
        "Job": "CEO"
    }

    response = requests.post(endpoint, payload)
    response_body = response.json()
    print("Response :", response_body)
    assert response.status_code == 201
    print("Elapsed Time :", response.elapsed.total_seconds())

pytest ResponseTime_test.py -s

How to add header to Python Requests

HOME

Headers = { “Authorization” : ”our_unique_secret_token” }

pip install -U requests

pip install -U pytest

import requests

ENDPOINT = 'https://reqres.in/api/users'


def test_add_header():
    request_body = {
        "name": "Vibha",
        "Job": "CEO"
    }

    header = {"Content-Type":  "application/json; charset=utf-8"}

    response = requests.post(ENDPOINT, request_body, header)
    print(response.json())
    print("Request Header", response.request.headers)
    print("Response Header", response.headers)
    assert response.status_code == 201
    assert response.headers["Content-Type"] == "application/json; charset=utf-8"

assert response.headers["Content-Type"] == "application/json; charset=utf-8"

pytest PostRequest_test.py -s

How to test PATCH Request Using Python Requests

HOME

pip install -U requests

pip install -U pytest

import requests

ENDPOINT = 'https://reqres.in/api/users/2'


def test_partiallyupdate_user():
    request_body = {
        "Job": "CFO"
    }

    response = requests.patch(ENDPOINT, request_body)
    print(response.text)
    assert response.status_code == 200
    response_body = response.json()
    assert response_body["Job"] == "CFO"

How to test DELETE Request Using Python Requests

HOME

pip install -U requests

pip install -U pytest

import requests

ENDPOINT = 'https://reqres.in/api/users/2'


def test_delete_user():

    response = requests.delete(ENDPOINT)
    assert response.status_code == 204

How to test PUT Request Using Python Requests

HOME

pip install -U requests

pip install -U pytest

import requests

ENDPOINT = 'https://reqres.in/api/users/2'


def test_update_user():
    request_body = {
        "name": "Vibha",
        "Job": "CTO"
    }

    response = requests.put(ENDPOINT, request_body)
    response_body = response.json()
    print(response_body)
    assert response.status_code == 200
    assert response_body["Job"] == "CTO"

How to test POST Request Using Python Requests

HOME

pip install -U requests

pip install -U pytest

import requests

ENDPOINT = 'https://reqres.in/api/users'


def test_create_user():

    response = requests.post(ENDPOINT, {"name": "Vibha", "job": "CTO"})
    response_body = response.json()
    print(response_body)
    assert response.status_code == 201
    assert response_body["name"] == "Vibha"
    assert response_body["job"] == "CTO"

def test_create_user1():
    payload = {
        "name": "Vibha",
        "job": "CTO"
    }

    response = requests.post(ENDPOINT, payload)
    response_body = response.json()
    print(response_body)
    assert response.status_code == 201
    assert response_body["name"] == "Vibha"
    assert response_body["job"] == "CTO"

Python Tutorials

HOME

Robot Framework

Configure Selenium with Python

Python Requests

PyTest Framework