DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • From Microservices to Agent Services: The Next Architectural Shift
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • MCP Elicitation: Human-in-the-Loop for MCP Servers

Trending

  • When RabbitMQ Accepts a Message but Does Not Route It to a Queue
  • Running a Self-Hosted WAF in Production: Practical Lessons From SafeLine
  • Decoupling a Data Pipeline From the Tables It Was Never Supposed to Depend On
  • Member Spotlight: Raghava Dittakavi

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. How to Do API Testing?

How to Do API Testing?

API endpoint example http://dzone.com/getuserDetails/{username} when you send the get request to that URL it returns the JSON response.

By 
Ganesh Hegde
·
Updated Jul. 07, 21 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
14.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

Nowadays API testing is an integral part of testing. There are a lot of tools like postman, insomnia, etc. There are many articles that ask what is API, What is API testing, but the problem is How to do API testing? What I need to validate.

Note: In this article, I am going to use postman assertions for all the examples since it is the most popular tool. But this article is not intended only for the postman tool. 

Let's directly jump to the topic.

Let's consider you have an API endpoint example http://dzone.com/getuserDetails/{{username}}  when you send the get request to that URL it returns the JSON response.

My API endpoint is http://dzone.com/getuserDetails/{{username}} 

The response is in JSON format  like below

JSON
 




xxxxxxxxxx
1
15


 
1
{
2
  "jobTitle": "string",
3
  "userid": "string",
4
  "phoneNumber": "string",
5
  "password": "string",
6
  "email": "[email protected]",
7
  "firstName": "string",
8
  "lastName": "string",
9
  "userName": "string",
10
  "country": "string",
11
  "region": "string",
12
  "city": "string",
13
  "department": "string",
14
  "userType": 0
15
}



In the JSON we can see there are properties and associated values. 

Now, For example, if we need details of the user with the username 'ganeshhegde' we need to send a GET request to http://dzone.com/getuserDetails/ganeshhegde 
dzone.com

Now there are two scenarios.

1. Valid Usecase: User is available in the database and it returns user details with status code 200

2. Invalid Usecase: User is Unavailable/Invalid user in this case it returns status with code 404 with not found message.

API Tests for Valid Requests

We are sending a request like below.

dzone.com


And Response is JSON is likeblow.


JSON
{
    "userId": "aaqere1d0d3d478d7d2e6s",
    "jobTitle": "Test Engineer",
    "phoneNumber": 0000006987,
    "email": "[email protected]",
    "firstName": "Ganesh",
    "lastName": "Hegde",
    "userName": "[email protected]",
    "country": "India",
    "city": "Bangalore",
    "department": null,
    "region": "APAC",
	"userType": 0
}


Expected STATUS :200 OK

How To Write API Tests for the Above Request and Response, What We Need To Validate?

Let's consider one by one

1.  Verify Status

First, you need to test whether response status is expected, In our case, we are expecting 200

Let's see how to validate 

JSON
 




x


 
1
pm.test("Verify Reponse Status 200", function() {
2
    pm.response.to.have.status(200);
3
});



2. Verify Response format

You need to think what is your expected response format, whether it is JSON, Text, or HTML file

In our case, it's a JSON file we can validate like below

JSON
 




xxxxxxxxxx
1


 
1
pm.test("Verify Response Format", function() {
2
    pm.response.to.be.json;
3
});



3.  Verify API Properties 

In the above example, we have properties like "userId", "jobTitle", "email" etc. we need to validate whether all properties, that are returned as a response.

Note: There can be some dynamic properties, you can add if and else block for those properties. 

JSON
 




xxxxxxxxxx
1
16


 
1
 
          
2
pm.test('Verify Properties', () => {
3
    response = pm.response.json();
4
    pm.expect(response).to.own.property("userId");
5
    pm.expect(response).to.own.property("jobTitle");
6
    pm.expect(response).to.own.property("phoneNumber");
7
    pm.expect(response).to.own.property("email");
8
    pm.expect(response).to.own.property("firstName");
9
    pm.expect(response).to.own.property("lastName");
10
    pm.expect(response).to.own.property("userName");
11
    pm.expect(response).to.own.property("country");
12
    pm.expect(response).to.own.property("city");
13
    pm.expect(response).to.own.property("department");
14
    pm.expect(response).to.own.property("region");
15
    pm.expect(response).to.own.property("userType");
16
});



4. Verify Data Type of Property Values

Consider the above example, We have a property called phone number where we are expecting only numbers, not a string, If it returns a string then something is wrong, when we have assertions for these, errors can be caught easily at an early stage

Let's see how to do it.

JSON
 




x


 
1
 
          
2
pm.test('Verify data type of property values', () => {
3
    response = pm.response.json();
4
    pm.expect(response.userId).to.be.a('string');
5
    pm.expect(response.jobTitle).to.be.a('string');
6
    pm.expect(response.phoneNumber).to.be.a('number');
7
    pm.expect(response.email).to.be.a('string');
8
    pm.expect(response.firstName).to.be.a('string');
9
    pm.expect(response.lastName).to.be.a('string');
10
    pm.expect(response.userName).to.be.a('string');
11
    pm.expect(response.country).to.be.a('string');
12
    pm.expect(response.city).to.be.a('string');
13
    pm.expect(response.department).to.be.a('string');
14
    pm.expect(response.region).to.be.a('string');
15
    pm.expect(response.userType).to.be.a('number');
16
});



5. Verify for Empty String Values, Null, 0

This is the common error we get in  API response. due to some internal code changes. Most often API response of some property values adds default values either null, 0, or ' ' (empty string). This needs to be validated.

JSON
 




xxxxxxxxxx
1
16


 
1
pm.test('Verify Empty string, null, 0 or  Default Values', () => {
2
    response = pm.response.json();
3
    pm.expect(response.userId,'Invalid UserID').to.be.not.oneOf([null,'',0]);
4
    pm.expect(response.jobTitle,'Invalid Job Title').to.be.not.oneOf([null,'',0]);
5
    pm.expect(response.phoneNumber,'Invalid Phonenumber').to.be.not.oneOf([null,'',0]);
6
    pm.expect(response.email,'Invalid Email').to.be.not.oneOf([null,'',0]);
7
    pm.expect(response.firstName,'Invalid First Name').to.be.not.oneOf([null,'',0]);
8
    pm.expect(response.lastName,'Invalid Last Name').to.be.not.oneOf([null,'',0]);
9
    pm.expect(response.userName,'Invalid User Name').to.be.not.oneOf([null,'',0]);
10
    pm.expect(response.country,'Invalid Country').to.be.not.oneOf([null,'',0]);
11
    pm.expect(response.city,'Invalid City').to.be.not.equal(null);
12
    pm.expect(response.department,'Invalid Department').to.be.not.oneOf([null,'',0]);
13
    pm.expect(response.region,'Invalid Region').to.be.not.oneOf([null,'',0]);
14
    pm.expect(response.userType,'Invalid User Type').to.be.not.oneOf([null,'']);
15
    
16
});



6. Verify Static Values for the Particular Request (Optional)

If your request has static values, then you can assert that too.

For example in our case userType is always 1 you can assert that.

JSON
 




x
5


 
1
pm.test('Verify Static Values', () => {
2
    response = pm.response.json();
3
    pm.expect(response.userType).to.equal(1);
4
});



We have created API Tests for Valid Request, It is equally important to have a negative test case.

Create Tests for Invalid Data

It is important to write negative tests, what happens if I pass an invalid user name 

invalid username

Let's consider scenarios again.

1. Validate Response Status

In the above, since it is an invalid request, we are expecting 404

We can write tests like below.

JSON
 




x


 
1
pm.test("Verify Reponse Status 404", function() {
2
    pm.response.to.have.status(404);
3
});



2. Validate Reponse Format

In the above case, it will be not JSON, rather it returns string just "Not Found"

Java
 




x


 
1
pm.test('Verify Response Format',()=>{
2
   pm.response.to.be.not.json;
3
   pm.expect(pm.response.text()).to.be.a('string');
4
})



3. Verify Response String

Unlike, Valid Request we know what will be response text in most of the cases we can directly assert the response string.

JSON
 




xxxxxxxxxx
1


 
1
pm.test('Verify Response Text',()=>{
2
   pm.expect(pm.response.text()).to.equal('Not Found');
3
})



Hope this article helps you in getting the context of API Tests

API Data Types JSON API testing Requests Testing Property (programming)

Opinions expressed by DZone contributors are their own.

Related

  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • From Microservices to Agent Services: The Next Architectural Shift
  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • MCP Elicitation: Human-in-the-Loop for MCP Servers

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook