Today is the 7th day in the API Testing challenge organized by WeTest Auckland. The challenge for the day is to complete the first exercise posted at The Club (Ministry of Testing).

The goal of the exercise is to execute some simple API calls (e.g. GET / POST requests) using as many tools as possible.

The first step is to find a publicly available API that we can utilize to practice API testing (This was covered in day 5 of the challenge). Here is a list to choose from:

  • http://wiremock.org/ - This is a simulator for HTTP-based APIs. What is cool about wiremock is that it provides hosted API examples, which we can directly call. It also allows us to change these API through an easy web user interface. Register and give it a try
  • https://reqres.in/ - reqres also provides a hosted REST API, similar to wiremock. However, it doesn’t provide the ability to change APIs, and doesn’t require a registration
  • https://thronesdb.com/api - The ThronesDB Public API is available for anyone to access services associated with ThronesDB game data. This API is provided for use in deck builders, card databases, tournament managers…
  • https://developer.marvel.com/docs - This mainly provides only APIs using the GET method, and requires a registration to generate an API key
  • JSON Server This is nice if you wish to create a fake REST API locally

More publicly available APIs can be found at: https://www.ministryoftesting.com/dojo/lessons/websites-to-practice-testing?s_id=19103

In this post, I will use http://reqres.in to send GET and POST requests.

For today’s exercise, I will use Postman to send a GET and POST request to https://reqres.in/.

GET REQUEST

  • This is the first API that we will test: https://reqres.in/api/users?page=1. This will return a JSON object showing the page passed, the number of users returned by page, the total number of users, the total number of pages, and a JSON array that contains information about the users in the provided page (Try it in the browser if you wish… or check how to send the request in Postman in the coming steps):
Image for post
Image for post
  • In postman, create a new request:
  • Fill in the request name and description, add it to a collection, and click Save:
Image for post
Image for post
  • Notice how the request appears in the left panel with the name provided
  • Notice that the request contains a METHOD field set by default to GET; let us not change it as the first request we are sending is a GET request:
Image for post
Image for post
  • Now enter the request URL in the field next to the METHOD field: https://reqres.in/api/users
  • In the “Params” tab below the URL, enter the parameters. In our case, we are passing the “page” parameter, and press Send:
Image for post
Image for post
  • We just sent the first GET request, and got the JSON response. Notice the status is 200 🎉 - this request doesn’t require any headers or authentication
  • Let us validate the response. Navigate to the “Tests” tab. It’s possible to write directly the validation script or pick some predefined scripts from the right panel in the “Tests” tab (select: status code: Code is 200) — Click the “Send” button
  • Notice that we have the Test Results showing 1/1 in the response panel. This didn’t show before adding the assertion
Image for post
Image for post
  • Let us write a small script that validates the info returned in the response is correct — validate that the total is 12
pm.test("Total number of users is 12", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.total).to.eql(12);
});

pm.test is just telling postman that this is a test. The first parameter is the message to be displayed to identify the test, and the second parameter is a function that performs the validation operation .

Inside of the function passed as a second parameter to the test, we are first storing the JSON response in a variable called jsonData (pm.response.json() returns the response as a JSON object), then we are asserting that the “total” key in the jsonData is equal to 12.

  • Click the “Send” button. Notice that we have 2/2 in the Test Results page under the response panel
Image for post
Image for post
  • Change the assertion, let’s assume we are expecting to have 11 returned as number of users.
pm.test("Total number of users is 11", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.total).to.eql(11);
});

Click the “Send” button. Notice the test results, we have a failure as the response returned has a total equal to 12, while we are expecting 11:

Image for post
Image for post

POST Request

  • We are going to create a new user by sending a POST request. In Postman, create a new request, change the METHOD to POST and enter the URL: https://reqres.in/api/users
  • In this case, we need to pass a name and a job. Otherwise, a new user will be created without a name. Some APIs would return an error saying that no name was passed, the one we’re testing would just create a user without a name (click the “Send” button and notice the returned response)
  • Let us send a name and a job as part of this request Go to the “Body” tab under the request panel → Select the “raw” radio button → Select JSON(application/json) instead of text → Enter {“name":”Ali", “job":"tester"} in the box below it. Click the “Send” button
Image for post
Image for post

Exercise: Add Tests in the Tests tab to validate the name and job returned in the response.

How can we know what to send as a request body? this should be part of the API documentation(for this request it can be found at: https://reqres.in)

Alternatively, if you don’t have enough documentation, the request can be inspected in the Chrome dev tools, and imported into postman. Please check the steps below:

  • In Chrome, navigate to: https://reqres.in
  • Open the dev tools and navigate to the “Network” tab
  • On the web page, click the “Create” API
  • Notice that a “users” request appeared in the “Network” tab, click it
  • Notice all of the request details there (if you scroll down under the “Headers” tab, you will notice something called “Request Payload”, that’s what should go under “Body” in Postman”

If you don’t wish to copy/paste these info into Postman, you can do the following:

  • Right click the users request in the Chrome dev tools
  • Click the Copy menu item
  • Click Copy as cURL
  • Go to Postman
  • Click the Import button (Located next to the “New” button)
  • Select “Paste Raw Text”, and paste the cURL you copied
  • Click Import
  • Now you have the request ready with all of the data needed, change the values as you wish

The below gif shows the described steps:

Image for post
Image for post

I hope this was helpful.

How about we try to send requests using another tool. In the coming section, we will create fake APIs, and use an HTTP client to send the requests. We will use JavaScript to do that.

Pre-requisites:

  • Install Node.js and npm. This site explains what are these and how to install them https://www.npmjs.com/get-npm
  • Install an IDE/Editor/Terminal — I use Vscode, it has its embedded terminal

Create a fake API

  • In your terminal, create a new directory. Name it “fake-api”: mkdir fake-api
  • Navigate to the new directory: cd fake-api
  • Let’s setup a new npm package. Run npm init. Keep the default values when asked questions about initialization
  • Install json-server: npm install json-server
  • Inside your directory, create a new JSON file. Name it books.json. Enter info about books using the following JSON format:
{"books": [{"id": 1,"title": "Harry Potter and the Philosopher's Stone","Author": "J.K. Rowling"},{"id": 2,"title": "Harry Potter and the Chamber of Secrets","Author": "J.K. Rowling"},{"id": 3,"title": "Harry Potter and the Prizoner of Azkaban","Author": "J.K. Rowling"},{"id": 4,"title": "Thinking, Fast and Slow","Author": "Daniel Kahneman"}]}
  • Probably you already know what will our APIs do. Start the JSON server: ./node_modules/.bin/json-server — watch books.json
  • In your browser, enter the following URL: http://localhost:3000/books/1. The first book entered should be returned. This is a GET request
  • We can also send a POST request by passing a payload including the following json object. Try it in Postman
{
"id": 5,
"title": "new-title",
"author": "new-author"
}

The new book object is added to the JSON array inbooks.json file.

Install and Use an HTTP Client

This HTTP client can replace a tool that we usually use to send and test requests. This kind of tools doesn’t come with an out-of-the-box list of features to facilitate the testing (e.g. pre-script, tests, etc. such as the ones provided by Postman). However, it would be enough to send a request.

It is possible to integrate tools such as Cucumber with the HTTP Client, which would allow us to write our test scenarios in a Gherkin syntax. For example, the request above would be as follows:

Given There is a list of books in the Library
When the user requests the first book by ID
Then 'Harry Potter and the Philosopher's Stone' will be returned

This kind of integration won’t be covered in this post. For now, let us install an HTTP client (axios) and send a simple request:

  • In a new instance of the terminal, install axios: npm i axios
  • Create a new file named get-book.js, where we are going to create the GET request. Here is the content:
const axios = require('axios');//Make a request for a book with a given IDaxios.get('http://localhost:3000/books/3').then( function (response) {//handle successconsole.log(response.data);}).catch(function (error) {//handle errorconsole.log(error)})
  • Now we need to run this file to send the request. In your terminal run the following command: node get-books.js
Image for post
Image for post
  • In the next steps, let’s cover a POST request, where we are going to add a new book to the list. Create a new js file named add-book.js
  • Add the following to the file:
const axios = require('axios');axios.post('http://localhost:3000/books', {"id": 5,"title": "My New Book","author": "Cool Author"}).then(function (response) {console.log(response.data);}).catch(function (error) {console.log(error.message);});
  • Go to the terminal and run node add-book.js
  • Go to your books.json file and notice how the new book got added

We have covered sending a GET request and POST request, using Postman, and HTTP Client. This is a basic implementation for both the fake APIs, and the requests submitted.

Thanks for reading. Your feedback is appreciated.

Software engineer (JS | REACT | Node | AWS | Test Automation)

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store