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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Commonly Occurring Errors in Microsoft Graph Integrations and How To Troubleshoot Them (Part 4)
  • Modify JSON Data in Postgres and Hibernate 6
  • Architecting a Comprehensive Testing Framework for API and UI Testing
  • Cypress API Testing: A Detailed Guide

Trending

  • MySQL to PostgreSQL Database Migration: A Practical Case Study
  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  • DGS GraphQL and Spring Boot
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  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 user avatar
Ganesh Hegde
DZone Core CORE ·
Updated Jul. 07, 21 · Tutorial
Likes (12)
Comment
Save
Tweet
Share
13.5K Views

Join the DZone community and get the full member experience.

Join For Free

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": "user@example.com",
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": "example@live.com",
    "firstName": "Ganesh",
    "lastName": "Hegde",
    "userName": "example@live.com",
    "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)
  • Modify JSON Data in Postgres and Hibernate 6
  • Architecting a Comprehensive Testing Framework for API and UI Testing
  • Cypress API Testing: A Detailed Guide

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!