Postman is a popular API testing tool that allows developers to automate and validate API responses efficiently. This guide provides examples of how to use variables, write tests, handle error responses, and perform asynchronous requests in Postman.
Using Variables in Postman
Variables in Postman help create dynamic values for API testing. The following example sets two variables: name and description using random data.
pm.test("Status code is 200",()=>{pm.response.to.have.status(200)})pm.test("Status code is not 200",()=>{pm.response.to.not.eql(200)})pm.test('Response body is empty',()=>{pm.response.to.have.body('')})pm.test('Status code is 404',()=>{pm.expect(res.code).to.eql(404)})pm.test("Has name property",function(){pm.expect(jsonData).to.have.property('name',pm.variables.get('update_name'))})pm.expect(jsonData).to.be.an('array')jsonData.forEach(link=>{pm.expect(link).to.have.keys('id','info_id','name','url').and.be.an('object')})pm.expect(jsonData[0]).to.have.property('name',pm.variables.get('new_link_name'))
Error Response Tests
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
pm.test("Status code is 400",()=>{pm.response.to.have.status(400)})letjsonData=pm.response.json()pm.test("Has error property",function(){pm.expect(jsonData).to.have.property('error')})letjsonErrorData=jsonData.errorpm.test("Has status property",function(){pm.expect(jsonErrorData).to.have.property('status',400)})pm.test("Has name property",function(){pm.expect(jsonErrorData).to.have.property('name',"ApplicationError")})pm.test("Has message property",function(){pm.expect(jsonErrorData).to.have.property('message',"Name exist")})
Performing Asynchronous Requests
Postman supports asynchronous requests using callback functions. The following example demonstrates an async request for logging in and finding a user by email.
Postman provides a powerful framework for API testing, allowing developers to automate requests, validate responses, and handle errors effectively. By leveraging variables, test scripts, and asynchronous functions, developers can ensure API reliability and performance.