Chaining request data in Postman - Build an Automation Script
/* POST /createUser request Tests tab script */ pm.test('POST status is 201', () => { pm.response.to.have.status(201); }); const responseJson = pm.response.json(); pm.test('Response has id', () => { pm.expect(responseJson).to.have.property('id'); }); // Save id to environment variable for next request pm.environment.set('userId', responseJson.id); /* GET /getUserDetails request Pre-request Script */ // Use the saved userId in the request URL const userId = pm.environment.get('userId'); pm.variables.set('userId', userId); /* GET /getUserDetails request Tests tab script */ pm.test('GET status is 200', () => { pm.response.to.have.status(200); }); const getResponse = pm.response.json(); pm.test('Name is John', () => { pm.expect(getResponse.name).to.eql('John'); }); pm.test('Job is Developer', () => { pm.expect(getResponse.job).to.eql('Developer'); });
The POST request test script first checks the response status is 201, which means the user was created successfully. It then parses the JSON response and asserts that an 'id' field exists. This 'id' is saved to an environment variable userId for use in the next request.
In the GET request, the pre-request script retrieves the saved userId and sets it as a variable to be used in the request URL path parameter.
The GET request test script verifies the response status is 200, meaning the user details were fetched successfully. It then asserts that the returned 'name' and 'job' fields match the values sent in the POST request, confirming the chaining of data between requests.
This approach uses Postman's environment variables to pass data between requests, and pm.test with clear messages to make debugging easier.
Now add data-driven testing with 3 different user data sets for the POST request and verify each GET response accordingly.