How To Use Postman To Test Rest Web Service
Getting Started with Postman for REST API Testing
Postman is a powerful and popular platform for testing and interacting with REST APIs. Its user-friendly interface, robust features, and wide range of capabilities make it ideal for both beginners and experienced testers. In this guide, we’ll explore how to use Postman to test REST web services, covering fundamental concepts and practical examples.
Creating a New Request
-
Open Postman: Start by launching the Postman app or visiting the Postman web interface. You’ll see the Postman workspace.
-
Create a New Request: Click on the “New” button and select “Request” from the menu. This will open a new request tab.
Defining the Request Details
-
HTTP Method: Select the relevant HTTP method for your API endpoint. Common methods include GET, POST, PUT, DELETE, PATCH, and more.
-
URL: Enter the complete URL of the API endpoint you want to test.
-
Headers: Add any necessary headers to your request. This could include authentication tokens, content type, or other custom headers.
-
Body: For POST, PUT, or PATCH requests, you need to provide data in the request body. Postman offers different options for body data input:
- Form Data: For simple key-value pairs.
- JSON: For structured data in JSON format.
- Raw: For sending raw text or code.
- Binary: For uploading files.
Example: Let’s test the GET
method of an API endpoint that retrieves user information using their ID.
URL: https://api.example.com/users/123
Request Headers:
Content-Type: application/jsonAuthorization: Bearer your_access_token
Sending the Request and Viewing Responses
-
Send the Request: Click the “Send” button to execute the request.
-
View the Response: Postman will display the response from the server, including the status code, headers, and response body.
Example: The response from the GET
request above could be:
Status Code: 200 (OK)
Response Headers:
Content-Type: application/json
Response Body (JSON):
{ "id": 123, "name": "John Doe", "email": "john.doe@example.com"}
Writing Assertions for Response Validation
Postman’s Test tab is critical for verifying your API’s behavior. You can add code snippets (called “tests”) to validate the response based on specific criteria.
Example:
Test Script:
pm.test("Status code is 200", function () { pm.response.to.have.status(200);});
pm.test("Response body has name 'John Doe'", function () { pm.expect(pm.response.json().name).to.eql("John Doe");});
pm.test("Response body has a valid email address", function () { pm.expect(pm.response.json().email).to.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/);});
Explanation:
pm.test()
: Defines a test case with a descriptive name.pm.response.to.have.status()
: Checks the HTTP status code.pm.expect()
: Combines with Chai’s assertions for complex validations.
Creating API Collections and Environments
Postman Collections organize your API requests into logical groups, making it easier to manage your tests. Environments allow you to store variables like base URLs, authentication details, and other configuration values. This lets you switch between different testing environments easily.
Example:
Collection: “User API”
Requests:
GET /users
(fetches all users)GET /users/:id
(fetches a specific user)POST /users
(create a new user)
Environment: “Prod” or “Dev” holding the appropriate base URLs and authentication details.
Advanced Techniques
Postman offers numerous advanced features for API testing:
- Data-Driven Testing: Using external data sources (e.g., CSV, JSON) to execute multiple tests with varying inputs.
- Mocking and Stubbing: Simulating API responses for testing scenarios where the actual API is unavailable or under development.
- Pre-request Scripts: Executing code before sending a request to modify request parameters or dynamically generate data.
- Post-Request Scripts: Code that runs after a request is sent, enabling more complex response validation.
- Webhooks and Integrations: Triggering actions based on API events, like sending notifications to Slack or integrating with other tools.
Practical Example: Testing a Todo API
Let’s create a Postman collection for testing a simplified TODO API:
1. Create a Collection:
- Go to “Collections” in Postman and create a new collection named “Todo API”.
2. Add Requests:
- Add a
GET
request for viewing all todos.- Request URL:
https://api.todoapp.com/todos
- Add a test to verify the status code is 200 and check if the response body contains a list of todo items.
- Request URL:
- Add a
POST
request for creating a new todo.- Request URL:
https://api.todoapp.com/todos
- Set the HTTP method to “POST”.
- Add a body with a JSON structure containing the new todo’s title and description.
- Include tests to check the status code and validate the created todo’s information in the response.
- Request URL:
- Add a
PUT
request for updating an existing todo.- Request URL:
https://api.todoapp.com/todos/:id
(replace:id
with the actual todo ID) - Set the HTTP method to “PUT”.
- Add a body with updated details for the todo.
- Include tests to check the status code and validate the updated todo’s information.
- Request URL:
- Add a
DELETE
request for deleting a todo.- Request URL:
https://api.todoapp.com/todos/:id
(replace:id
with the todo ID) - Set the HTTP method to “DELETE”.
- Add tests to verify the status code and ensure the todo is deleted successfully.
- Request URL:
3. Create Environments: (Optional)
- You can create different environments (e.g., “Dev,” “Staging,” “Prod”) and configure the base URLs and other settings for each.
4. Run and Manage Tests:
- Run individual requests or the entire collection.
- View test results, analyze reports, and troubleshoot issues.
Sample Code Snippets:
- Test for GET request to fetch all todos:
pm.test("Status code is 200", function () { pm.response.to.have.status(200);});
pm.test("Response body is an array of todos", function () { pm.expect(pm.response.json()).to.be.an('array');});
- Test for POST request to create a new todo:
pm.test("Status code is 201", function () { pm.response.to.have.status(201);});
pm.test("Response body includes created todo details", function () { pm.expect(pm.response.json().title).to.equal("New Todo Title");});
Conclusion
Postman empowers both developers and testers to confidently interact with REST APIs, perform thorough testing, and ensure the quality and reliability of their web applications. By leveraging its user-friendly features, powerful test scripting capabilities, and advanced options, you can effectively test and manage your REST APIs throughout the development lifecycle.