How to Use pm.response in Postman for API Testing
In Postman,
pm.response lets you access the HTTP response of your API request inside test scripts. You can use it to check status codes, headers, and response body content to validate your API behavior.Syntax
The pm.response object provides properties and methods to inspect the API response. Key parts include:
pm.response.code: Gets the HTTP status code.pm.response.json(): Parses and returns the response body as a JSON object.pm.response.text(): Returns the response body as plain text.pm.response.headers.get('Header-Name'): Retrieves a specific header value.
javascript
pm.test('Status code is 200', () => { pm.response.to.have.status(200); }); const responseBody = pm.response.json(); pm.test('Response has userId', () => { pm.expect(responseBody).to.have.property('userId'); });
Example
This example shows how to check if the response status is 200 and if the JSON response contains a name property.
javascript
pm.test('Status code is 200', () => { pm.response.to.have.status(200); }); const data = pm.response.json(); pm.test('Response contains name property', () => { pm.expect(data).to.have.property('name'); });
Output
PASS Status code is 200
PASS Response contains name property
Common Pitfalls
Common mistakes when using pm.response include:
- Trying to parse non-JSON responses with
pm.response.json(), which causes errors. - Not waiting for the response before accessing
pm.response(usually handled by Postman automatically). - Using incorrect header names or case-sensitive keys when accessing headers.
Always check the response content type before parsing.
javascript
/* Wrong: Parsing text response as JSON causes error */ // const data = pm.response.json(); // Fails if response is plain text /* Right: Check content type before parsing */ if (pm.response.headers.get('Content-Type') && pm.response.headers.get('Content-Type').includes('application/json')) { const data = pm.response.json(); pm.expect(data).to.have.property('id'); } else { pm.expect(pm.response.text()).to.be.a('string'); }
Quick Reference
| pm.response Property/Method | Description |
|---|---|
| pm.response.code | Returns the HTTP status code of the response |
| pm.response.json() | Parses and returns the response body as JSON |
| pm.response.text() | Returns the response body as plain text |
| pm.response.headers.get('Header-Name') | Gets the value of a specific response header |
| pm.response.to.have.status(code) | Asserts the response status code |
Key Takeaways
Use pm.response to access and validate API response data in Postman tests.
Always check response content type before parsing with pm.response.json().
Use pm.response.to.have.status() to assert HTTP status codes easily.
Access headers with pm.response.headers.get('Header-Name') using correct casing.
Write clear tests to verify response structure and content for reliable API testing.