From vision to reality, explore our blog and articles. Contact us to turn your ideas into success.
Contact us.
By Next SolutionLab on 2024-10-23 22:24:57
There are many helpful libraries for automating API testing, such as Requests for Python and for JavaScript, which offer reusable code snippets for test cases. While these libraries are valuable for automation engineers, another tool simplifies API testing for those without programming skills—. It is an API testing platform that enables efficient and thorough testing. Postman offers:
1. A user-friendly interface that makes it easy to visualize and manage each aspect of the API lifecycle.
2. Pre-built code snippets for test verification and generating test data.
3. Versatile options, such as testing in different environments, managing servers, documenting APIs, and collaborating with
team members.
This blog post aims to introduce Postman as a valuable tool for semi-automated API testing, featuring practical examples with screenshots. It assumes you have a basic understanding of APIs; if not, I suggest reading my previous article—.
Postman was created in 2012 by Abhinav Asthana, a software engineer who wanted to streamline API testing. It has since become a platform that helps engineers design, build, and test APIs more efficiently. By simplifying each stage of the API lifecycle, Postman enhances collaboration, allowing teams to create better APIs faster.
At its core, Postman serves as a centralized hub for storing, cataloging, and collaborating on all API-related resources. It can manage API specifications, documentation, workflows, test cases, results, metrics, and more. Today, Postman boasts a user base of over 20 million people.
You can download Postman from , selecting the appropriate version for your operating system. Mac users should ensure they download the version compatible with their laptop’s chip.
For those who prefer not to install the desktop app, Postman also has a . To use it, you need to if you don't already have one.
While the desktop app does not require a Postman account for basic use, registering unlocks additional features.
Postman’s main workspace serves as a central location where all API-related activities can be managed. Workspaces help organize API tasks and facilitate collaboration across teams. Within a workspace, you can access collections, environments, mock servers, monitors, and other Postman tools. A collection is a set of saved API requests, while environments consist of variables that can be used within those requests.
Figure : Workspace - the overview screen of Postman
As mentioned above, we group all API requests in a collection, but we also group our API tests in a collection. This means that the collection is a root folder of our project. Inside it, we can organize our work in folders and subfolders. It is up to you to decide how you would like to structure the collection, however, the most common practice is that:
1. Folders are created for every endpoint. The name of the folder is usually the name of the endpoint.
2. An Integration tests folder can also be created where we can place API tests that test the connection between different API endpoints.
Namely, when we want to chain multiple API requests to test, for example, if the data in one endpoint is present in the other
related endpoint.
Figure: Postman collection structure
For the examples in this blog post, I will use the provided by Swagger. It’s an excellent resource for understanding how API requests and responses work in practice. I encourage you to take the time to explore the documentation for any API you work with. Reviewing the documentation helps you gain a thorough understanding of the API's functionality, the required parameters for each request, and the types of responses you can expect. You can access the documentation for the Petstore API .
Figure : Exploring Petstore API documentation
In the documentation, the base URL of the API is written as: petstore.swagger.io/v2. Since the base URL is the same for every API request, it makes sense that we store it as a variable in our collection so that we can reuse it. To do that, follow these steps:
1. Select the collection in “Collections” tab.
2. In the collection’s view, select “Variables” tab.
3. Populate “Variable name”, “Initial value” and “Current value” columns with respective values: baseUrl and https://petstore.swagger.io/v2.
Figure : Create collection variable
The first request we’re going to create in Postman is the GET request for finding pets by status. The endpoint for this request is /pet and the request parameter is /findByStatus. We can also observe from the documentation that this request requires a status query parameter and the values for the status that are accepted are: available, pending and sold.
Figure : Documentation of /pet/findByStatus API request
To add the request in Postman, follow these steps:
1. Right click on the collection in the “Collections” tab.
2. Choose the “Add folder” option. Name the folder “pet” because we will place all requests for /pet endpoint in this folder.
3. Right click on the “pet” folder and choose the “Add request” option.
The request view will be displayed. We should populate all the required information for the request here. For now, we will set just a name for the request.
Figure : Adding a folder and request in Postman
GET is already set as the default option in the drop down for request method, therefore we don’t need to change it. We should enter the request URL, here we will insert {{baseUrl}}/pet/findByStatus. If you remember, we’ve already added baseUrl as a collection variable, so we can use its value by wrapping the variable name in curly brackets. This way, we don’t need to specify the full URL in every request. Under the “Params” tab, we can enter query parameters. For our request, we need to enter the “status” query parameter and any accepted status as value. We can use “available” as a status value for this example.
Now that we have entered all necessary data, we can hit the “Send” button to send the request and observe the response we receive from the server. The response is received in the “Response” section at the bottom of the view. The data is received in JSON format, and we can easily observe all the information of available pets, like name, photo URLs, categories, etc.
Figure : Sending GET request in Postman and observing the response
The next step is to add tests for the response we received. We want to test if we received a successful response (status code is 200) and if the data in the response body contains a pet with the name “doggie”. Tests can be added under the “Tests” tab. On the right side, next to the input field, we already have predefined JavaScript code snippets for most common test cases. Scroll down a bit, and look out for the snippets with names: “Status code: Code is 200” and “Response body: JSON value check”. These snippets can be used for our test cases. If you’re familiar with JavaScript, you can add more code here and test the response more thoroughly.
For our simple test we will modify the second code snippet, so that from the list of all available pets we will check if the first pet has the name “doggie”.
pm.test("First pet check name", function () {
var jsonData = pm.response.json();
pm.expect(jsonData[0].name).to.eql("doggie");
});
To run the tests, we have to send the request again. Test results will be available in the “Response” section under the “Test Results” tab. If you click on this tab, you can easily check which tests passed or if some tests failed.
Figure : Adding and executing tests, and observing test results
Our second test case will fail sometimes because every time the request is sent, the API responds with available pets at that particular time. This means that “doggie” may not be available the next time we send the request and that’s why the test might fail. We should design our test cases to be better than the simple example above, they should always be consistent with the end use case we want to check and with the API state.
Figure : Test might fail if you run it again after some time has passed
We can also check and test what happens when we pass invalid status value. The documentation states that in this case we should receive the 400 response status code. We can add this example in our request, also we can test this expectation. We can duplicate our existing request by right clicking on it and choosing the “Duplicate” option.
Figure : Adding a duplicate request
We set a new name for the request so that we distinguish that it is for an invalid status code. Also, we modify the value of the “status” query parameter and add an arbitrary value. In the tests, we remove the second test case because we don’t need it for this request, but we also modify the first test case to check if we receive the 400 response status code.
pm.test("Status code is 400", function () {
pm.response.to.have.status(400);
});
If we send the request, the test should pass.
How about we add a new pet with the name Dogo to the pet store? For this we can use the POST request, which is the only request that changes the server by adding a new object. From the documentation, we can see that the endpoint for adding a new pet is just /pet without any request parameter. A request body is mandatory, as is with every POST request. We can see from the documentation that the body should be given in JSON format and the required data that should be provided is pet’s name and photoUrls.
Figure : Documentation of POST /pet API request
Similarly, as we did with the GET request, we will add the POST request under the “pet” folder:
1.Select “POST” from the drop down menu.
2. Enter {{baseUrl}}/pet in the request URL input field.
3. Select the “Body” tab below the request URL input field to add the JSON request body.
4. Choose the “raw” option and select JSON from the last drop down view in the row.
In the input field below the body format options, we should enter the following body:
{
"name": "Dogo",
"photoUrls": [
"https://www.akc.org/wp-content/uploads/2017/11/Dogo-puppy.jpg"
]
}
Figure : Adding POST request in Postman
If we execute this request by pressing the “Send” button, we should receive a successful response. The response should contain data we already provided with additional information, like ID.
Figure : The response from the request
It's fairly simple to construct a test for this response, we want to make sure that the added pet is indeed with the name Dogo and with the correct photo URL. Similarly as with the GET request, we can use already existing snippets for checking the response status code and values from the JSON response. Our tests should look like this:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("New pet response check", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.name).to.eql("Dogo");
pm.expect(jsonData.photoUrls[0]).to.eql("https://www.akc.org/wp-content/uploads/2017/11/Dogo-puppy.jpg");
});
If we run the tests, they should pass.
Figure : Test results for adding new pet request
We can also play around with the request body and try to send invalid data or data without mandatory values. It’s recommended to construct tests with expected response codes, trying to cover as many negative and positive scenarios as possible.
What if you want to change the name of your pet and update the status to sold? We know that the PUT request can modify the server so that an existing object can be updated with new data. But from all the pets in the store, how will the server know which one is your pet? If you observe the response from above closely, where we added the pet to the store with the POST request, you’ll notice that there is an ID in the data. This ID is the identification of the pet whose data we want to update. We can use this ID in our request for updating the name of our pet and the status. However, it’s not optimal to copy and paste the ID. We want this ID to be stored as a variable and then used in our update request. Luckily, Postman allows us to store data from responses as variables too, just like we stored the base URL in collection variables. Let’s store the ID of the previously created pet. In Postman, follow these steps:
1. Open the POST request you created previously.
2. Go to the “Tests” tab.
3. From the snippets on the right, choose the one with the name “Set a collection variable”.
The snippet should be copied at the end of the test. Move the snippet in “New pet response check” test and modify it like so
pm.collectionVariables.set("petId", jsonData.id);
4. Run the tests again. This is important so that with the new code snippet, the ID can be saved to collection variables.
You can check if your ID is stored by clicking on the collection, then selecting the “Variables” tab. The petId variable should be listed below the baseUrl variable.
Figure : petId saved as collection variable after test execution of adding new pet
Now that we have the identification of our pet we can update the name and status with the PUT request. From the documentation, we can see that everything is the same as with the POST request, the only difference is in the request method. Repeat the same steps as with the POST request, but make sure to select “PUT” from the drop down menu for the request method and send the following request body:
{
"id": {{petId}},
"name": "Lucky",
"status": "sold"
}
We wrapped our saved pet ID with curly brackets in the request body. The created request in Postman should like this:
Figure : PUT request to update the data of our pet
Run the request and observe the response. New data should be visible in the response.
Figure : The response of the PUT request
We can add similar tests as with the POST request to check if the pet’s name and status are updated. The tests should look like this:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("Pet update check", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.name).to.eql("Lucky");
pm.expect(jsonData.status).to.eql("sold");
});
When we run the tests, they should pass.
Now, let’s imagine that the pet store has sold the dog Lucky and he is now happily living with me. I can safely delete the data of my pet from the server by using the DELETE request. The documentation states that the pet ID should be provided as a request parameter to the endpoint.
Figure : Documentation of DELETE /pet API request
We already have the ID stored in the collection variables, therefore we can use it for the DELETE request as well by wrapping it in curly brackets in the request URL. Here is what the request in Postman should look like:
Figure : DELETE request to delete the data of a pet
Before executing this request with the “Send” button, we should add tests first. This is because the DELETE request tests are more informative than the response body we receive. We can add one test to check if we receive the successful response status code 200. However, we can also check if the pet is actually deleted by using the GET request with the /pet/{petId} endpoint, which gives us information about a given pet with a specific ID.
For this request we should receive a 404 (not found) response status code because we previously deleted the pet with the stored ID and it should no longer exist. We can check this by sending the request in code via an already existing code snippet. This code snippet can be found under “Send a request” name. In the test, for this request, we expect that the response has a 404 (not found) status code, so it should look like this:
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
​
pm.sendRequest(pm.variables.get("baseUrl")+"/pet/" + pm.variables.get("petId"), function (err, response) {
pm.test('Get pet data after deletion', function() {
pm.expect(response.code).to.eql(404)
});
});
Now we can execute the request and observe test results. Tests should have passed.
Figure : Test results for deleting a pet request
In this post, we explored the four most common API request methods—GET, POST, PUT, and DELETE—by implementing them in Postman. We examined the responses, added tests for the expected data, and analyzed the results. Based on our example test cases using the Petstore API, it’s clear that Postman is a straightforward and user-friendly tool for exploring and testing APIs.
Here are some key benefits of using Postman for API testing:
User-Friendly Interface: Postman is easy to navigate, making it accessible for users of all skill levels.
Enhanced Visualization: APIs can be visualized more effectively, simplifying the understanding of their structure and functionality.
Collection Sharing: Stored API requests in a collection can be easily exported and shared with the entire team.
Pre-Built JavaScript Snippets: These snippets are particularly useful for those with little or no programming experience, enabling them to create effective tests.
Advanced Testing Capabilities: Automation engineers can build more complex tests with relative ease, fully automating the API by generating test data in pre-request scripts and managing variables in collections and environments.
Simplified Authorization and Authentication: Postman makes it easy to handle API authorization and authentication.
Environment Flexibility: The same API tests can be executed across different environments.
Documentation and Monitoring: APIs can be documented and monitored effectively within Postman.
While the tests we performed here were relatively simple, real-world scenarios often require more comprehensive testing, thorough data validation, and adherence to specific use case scenarios. If you’re interested in learning more about writing tests in Postman, check out . You can also explore their to discover additional features for API exploration and testing.
At Next Solution Lab, we are dedicated to transforming experiences through innovative solutions. If you are interested in learning more about how our projects can benefit your organization.
Contact Us