Requests api testing python

How To Do API Testing Using Python Requests

In the previous article, we have seen What API is, What and How API testing should be performed, and how we can test APIs using the Postman tool. We have also learnt the rest assured framework for API automation. In this post, we will learn about the Python requests module and how we can perform API testing Using Python requests library.

Can Python Be Used For API Testing?

Python is a popular, high-level, object-oriented programming language with a simplified syntax and supports many libraries and frameworks.

A few reasons are listed below why Python is a good choice for API testing:

  1. Simple Syntax: Due to its simple syntax Python is easy to learn and use.
  2. Large Ecosystem: Python has a large ecosystem of libraries and frameworks that support API testing. Python supports numerous third-party libraries for making HTTP requests, handling responses, parsing data formats like JSON and XML, and validating responses.
  3. Multiple Protocol support: Python provides support for different protocols like HTTP, Rest, SOAP, and GraphQL.It is convenient to automate all these using a single language.
  4. Data manipulation and validation: It is very easy to manipulate and validate data in Python due to Python’s built-in libraries and integration with third-party libraries.
Читайте также:  Submitting form data in php

API Testing Using Python Requests Module

Python provides several libraries that can be used for API testing. Some of them are listed below.

What is Python Requests Library?

Python Requests is a very popular and very powerful library that supports HTTP requests. It is commonly used for API testing and supports cookies, sessions and authentication as well. This module is also widely used for web scraping.

Prerequisite:

Installation of Python Requests Module

a) Using Pycharm IDE

  1. If you are using Pycharm IDE then you need to install the Request library. Execute the below command using pip.

3. Create a new project folder and open it in PyCharm.

4. Create a new class file and import all the dependencies as mentioned below.

import requests import json import pytest

b) How To Setup VSCode For Python API Testing

If you don’t have Pycharm IDE then you can use VSCode following below mentioned steps.

  1. Create a new project directory and open it in VS code.
  2. Go to the Extensions view ( Ctrl+Shift+X ), search for “Python” and install the official Python extension by Microsoft.
  3. Set up a virtual environment for Python.
    • Open the integrated terminal in VS Code and create a virtual environment by running the following command in the terminal:

4. Activate the virtual terminal by using the below command.

5. Now Install the required libraries using this terminal.

pip install pytest requests

How to Use Python Requests with REST APIs

I will be using Reqres API for this tutorial.

1)Go to the project folder and Create a new file, name it “testAPI.py”.

2)Import the required packages.

3)Write a Script for automating GET, Post, Put and Delete calls.

1)How Request Data With GET

The GET method is used to get the resource from the server and returns 200 if successful.

import requests import json import pytest ENDPOINT = 'https://reqres.in/api/' USER = 'users/2' def test_get_endpoint(): response = requests.get(ENDPOINT+USER) assert response.status_code==200 print(response)

requests. get() method hit the provided endpoint and saves the response. We are using the “assert” keyword from the pytest module to validate the response code.

2)Sending Post Request with Python Requests

The post method is used to create new resources on the server. It returns 201 or 200 after the successful request.

Requests Library Post Syntax

requests.post(URL, data=[data], json=[json], headers=[headers], cookies=[cookies], files=[files] arguments)
  1. Specify the data type that needs to be sent in the request.
  2. Call requests.post() method with the targeted Endpoint.
  3. Provide request payload.
  4. Validate the status code.
import requests import json import pytest ENDPOINT = 'https://reqres.in/api/' def test_post_request(): payload = < "email": "eve.holt@reqres.in", "password": "cityslickaa" >response = requests.post(ENDPOINT + "login",json=payload) assert response.status_code==200 json_response =json.loads(response.text) token = json_response["token"] print(token)

“json. loads()” method of the JSON module parses the response string and converts it into a Python dictionary that helps in accessing JSON easily within the code.

3)Put Request with Python

Put requests are used to update or create a new resource on the server.

1)Send a post request to create a new resource.

2)Validate the response code.

3)Verify that the resource is updated.

4)Send a put request to update the resource.

6)Validate response JSON for updated data.

POST request for resource creation

import requests import json import pytest ENDPOINT = 'https://reqres.in/api/' def test_createUser_request(): payload = < "name": "morpheus01", "job": "leader" >response = requests.post(ENDPOINT + "users",json=payload) assert response.status_code==201 json_response =json.loads(response.text) if "id" in json_response: print(id) else: print("not found") 

A new user is created with the name ‘morpheus01’ having a job as a leader. Now we want to modify the job for this user. We will use put request to update the job as a businessman.

PUT request to modify the resource

def test_updateUser_request(): payload = < "name": "morpheus01", "job": "businessman" //Job value is changed >response = requests.put(ENDPOINT + "users/2",json=payload) assert response.status_code==200 json_response =json.loads(response.text) job= json_response["job"] print(job) assert response.json()["job"] == "buisnessman" //Should pass assert job == "buisnessman" //Should pass assert json_response.get('job') == 'leader'//Should fail as job is updated 

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.

4)Delete with Python Requests Module

Delete verb is used to remove the resource from the server. Delete requests can return response codes like 200,202,204 or 404.

1)Delete the newly created user

2) Validate the status code.

def test_deleteUser_request(): response = requests.delete(ENDPOINT + "users/2") assert response.status_code==204

We have completed the CRUD operation automation using the Python Requests library in this module. Refer to the complete code for this post below.

import requests import json import pytest ENDPOINT = 'https://reqres.in/api/' USER = 'users/2' def test_get_endpoint(): //GET Request response = requests.get(ENDPOINT+USER) assert response.status_code==200 print(response) def test_createUser_request(): //POST Request payload = < "name": "morpheus01", "job": "leader" >response = requests.post(ENDPOINT + "users",json=payload) assert response.status_code==201 json_response =json.loads(response.text) if "id" in json_response: print(id) else: print("not found") if not (id is None): print("value is present for given JSON key") print(id) else: print("value is not present for given JSON key") def test_updateUser_request(): //PUT Request payload = < "name": "morpheus01", "job": "buisnessman" >response = requests.put(ENDPOINT + "users/2",json=payload) assert response.status_code==200 json_response =json.loads(response.text) job= json_response["job"] print(job) assert response.json()["job"] == "buisnessman" assert job == "buisnessman" assert json_response.get('job') == 'leader' def test_deleteUser_request(): //DELETE Request response = requests.delete(ENDPOINT + "users/2") assert response.status_code==204

To execute all these tests together go to the terminal and type below mentioned command.

python -m pytest -v [testFileName] python -m pytest -v test-api.py

You will see the final result of your execution in the terminal.

Источник

Writing tests for RESTful APIs in Python using requests – part 1: basic tests

Recently, I’ve delivered my first ever three day ‘Python for testers’ training course. One of the topics that was covered in this course is writing tests for RESTful APIs using the Python requests library and the pytest unit testing framework.

In this short series of blog posts, I want to explore the Python requests library and how it can be used for writing tests for RESTful APIs. This first blog post is all about getting started and writing our first tests against a sample REST API.

Getting started
To get started, first we need a recent installation of the Python interpreter, which can be downloaded here. We then need to create a new project in our IDE (I use PyCharm, but any decent IDE works) and install the requests library. The easiest way to do this is using pip, the Python package manager:

Don’t forget to create and activate a virtual environment if you prefer that setup. We’ll also need a unit testing framework to provide us with a test runner, an assertion library and some basic reporting functionality. 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

passing requests test

In the response object, the headers are available as a dictionary (a list of key-value pairs) headers , which makes extracting the value for a specific header a matter of supplying the right key (the header name) to obtain its value. We can then assert on its value using a pytest assertion and the expected value of application/json .

How about checking the value of a response body element? Let’s first check that the response body element country (see the sample JSON response above) is equal to United States :

def test_get_locations_for_us_90210_check_country_equals_united_states(): response = requests.get("http://api.zippopotam.us/us/90210") response_body = response.json() assert response_body["country"] == "United States"

The requests library comes with a built-in JSON decoder, which we can use to extract the response body from the response object and turn it into a proper JSON object. It is invoked using the json() method, which will raise a ValueError if there is no response body at all, as well as when the response is not valid JSON.

When we have decoded the response body into a JSON object, we can access elements in the body by referring to their name, in this case country .

To extract and assert on the value of the place name for the first place in the list of places, for example, we can do something similar:

def test_get_locations_for_us_90210_check_city_equals_beverly_hills(): response = requests.get("http://api.zippopotam.us/us/90210") response_body = response.json() assert response_body["places"][0]["place name"] == "Beverly Hills"

As a final example, let’s check that the list of places returned by the API contains exactly one entry:

def test_get_locations_for_us_90210_check_one_place_is_returned(): response = requests.get("http://api.zippopotam.us/us/90210") response_body = response.json() assert len(response_body["places"]) == 1

This, too, is straightforward after we’ve converted the response body to JSON. The len() method that is built into Python returns the length of a list, in this case the list of items that is the value of the places element in the JSON document returned by the API.

In the next blog post, we’re going to explore creating data driven tests using pytest and requests.

Using the examples for yourself
The code examples I have used in this blog post can be found on my GitHub page. If you download the project and (given you have installed Python properly) run

pip install -r requirements.txt

from the root of the python-requests project to install the required libraries, you should be able to run the tests for yourself. See you next time!

Источник

Оцените статью