Testing REST APIs Using Postman
Course: Advanced Java Training
Topic: Testing REST APIs Using Postman
Course Link: Advanced Java Training Course
Demo Link: Register for a Free Course Demo
Website: JustAcademy
1. Introduction to REST API Testing
REST APIs allow applications to communicate over HTTP by exchanging data between clients and servers. In a Spring Boot application, REST APIs are commonly created using controllers, services, and repositories. Testing these APIs verifies that requests are processed correctly and that the server returns the expected status codes, headers, and response data.
Postman is an API development and testing tool that allows developers to send HTTP requests, inspect responses, organize API requests into collections, configure authentication, and automate tests using JavaScript.
For example, a Spring Boot application may provide endpoints to create, retrieve, update, and delete employee records. Postman can be used to test each endpoint without building a separate frontend application.
Why Is REST API Testing Important?
- Verifies that API endpoints behave according to requirements.
- Checks HTTP status codes and response formats.
- Identifies errors in request validation and exception handling.
- Tests authentication and authorization rules.
- Helps detect regressions after application changes.
- Supports integration testing between backend services.
- Reduces the need to repeatedly test endpoints manually through a frontend.
2. Learning Objectives
After completing this topic, learners should be able to:
- Understand the role of Postman in REST API testing.
- Create and configure HTTP requests.
- Test GET, POST, PUT, PATCH, and DELETE endpoints.
- Send JSON request bodies and configure headers.
- Inspect status codes, response headers, and response bodies.
- Test validation errors and exception responses.
- Write automated assertions using Postman's JavaScript scripting features.
- Use variables, environments, and collections.
- Test authentication and common API failure scenarios.
- Organize repeatable API test workflows.
3. Understanding REST APIs Before Testing
REST stands for Representational State Transfer. A REST API exposes resources through URLs and uses HTTP methods to perform operations on those resources.
Common HTTP Methods
| HTTP Method |
Purpose |
Example Endpoint |
| GET |
Retrieve a resource or collection. |
/api/employees |
| POST |
Create a new resource. |
/api/employees |
| PUT |
Replace or fully update a resource. |
/api/employees/1 |
| PATCH |
Partially update a resource. |
/api/employees/1 |
| DELETE |
Delete a resource. |
/api/employees/1 |
Example REST API URLs
GET http://localhost:8080/api/employees
GET http://localhost:8080/api/employees/1
POST http://localhost:8080/api/employees
PUT http://localhost:8080/api/employees/1
PATCH http://localhost:8080/api/employees/1
DELETE http://localhost:8080/api/employees/1
These URLs are illustrative. They will work only if the Spring Boot application is running and the corresponding endpoints have been implemented.
4. Introduction to Postman
Postman provides a request builder where a developer can select an HTTP method, enter a URL, configure query parameters and headers, add authentication details, and submit a request to a server.
Main Components of Postman
| Component |
Description |
| Request Builder |
Used to select the HTTP method and enter the endpoint URL. |
| Params |
Used to add query parameters to a request. |
| Authorization |
Used to configure supported authentication methods. |
| Headers |
Used to send metadata such as Content-Type and Accept. |
| Body |
Used to send JSON, form data, or other supported request payloads. |
| Response Viewer |
Displays the response body, status, headers, and timing information. |
| Scripts |
Provides pre-request and post-response scripting capabilities. |
| Collections |
Groups related requests into reusable API test suites. |
| Environments |
Stores variables for different application environments. |
5. Setting Up Postman and a Spring Boot Application
Step 1: Install or Open Postman
Postman can be used through its desktop application or supported web experience. Visit the official Postman download page to access the available options.
Step 2: Start the Spring Boot Application
Run your Spring Boot application using your IDE or the Maven wrapper. For a typical Maven project, you can use:
./mvnw spring-boot:run
On Windows, the command is commonly:
mvnw.cmd spring-boot:run
Confirm that the application starts successfully and is listening on the expected port, such as 8080.
Step 3: Create a New Request
- Open Postman.
- Create a new HTTP request.
- Select the required HTTP method.
- Enter the API endpoint URL.
- Configure parameters, headers, authentication, or body data as required.
- Click Send.
- Review the response and compare it with the expected result.
6. Creating a Sample REST API in Spring Boot
To understand API testing practically, consider a simple employee API. The following example exposes endpoints that Postman can call.
Employee Model
package com.example.demo.model;
public class Employee {
private Long id;
private String name;
private String email;
public Employee() {
}
public Employee(Long id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Sample REST Controller
package com.example.demo.controller;
import com.example.demo.model.Employee;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
private final Map<Long, Employee> employees =
new ConcurrentHashMap<>();
private final AtomicLong idGenerator = new AtomicLong();
@GetMapping
public Map<Long, Employee> getAllEmployees() {
return employees;
}
@GetMapping("/{id}")
public ResponseEntity<Employee> getEmployee(
@PathVariable Long id) {
Employee employee = employees.get(id);
if (employee == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(employee);
}
@PostMapping
public ResponseEntity<Employee> createEmployee(
@RequestBody Employee employee) {
Long id = idGenerator.incrementAndGet();
employee.setId(id);
employees.put(id, employee);
return ResponseEntity
.status(HttpStatus.CREATED)
.body(employee);
}
@PutMapping("/{id}")
public ResponseEntity<Employee> updateEmployee(
@PathVariable Long id,
@RequestBody Employee employee) {
if (!employees.containsKey(id)) {
return ResponseEntity.notFound().build();
}
employee.setId(id);
employees.put(id, employee);
return ResponseEntity.ok(employee);
}
@DeleteMapping("/{id}")
public ResponseEntity<Void> deleteEmployee(
@PathVariable Long id) {
Employee removed = employees.remove(id);
if (removed == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.noContent().build();
}
}
Important: This is a learning example that stores records in memory. Data disappears when the application restarts. It is not a production-ready persistence implementation and does not include input validation, authentication, or a PATCH endpoint.
7. Testing a GET Request in Postman
The GET method retrieves data from the server without creating or modifying a resource.
Example: Retrieve All Employees
- Create a new request in Postman.
- Select GET.
- Enter
http://localhost:8080/api/employees.
- Click Send.
- Inspect the status code and response body.
For an empty in-memory collection, the example controller may return an empty JSON object.
{}
After an employee has been created, the response will contain the stored employee records.
Example: Retrieve One Employee
GET http://localhost:8080/api/employees/1
If employee 1 exists, the response may look like this:
{
"id": 1,
"name": "Aarav Sharma",
"email": "[email protected]"
}
If the employee does not exist, the example controller returns 404 Not Found.
What Should Be Tested?
- Correct status code for an existing employee.
- Expected response fields and values.
- Behavior when the requested employee does not exist.
- Response content type.
- Correct handling of invalid path parameters.
8. Testing a POST Request in Postman
The POST method is commonly used to create a new resource.
Steps to Send a POST Request
- Select POST as the HTTP method.
- Enter
http://localhost:8080/api/employees.
- Open the Body tab.
- Select raw and choose JSON.
- Enter the request payload.
- Click Send.
Sample JSON Request Body
{
"name": "Aarav Sharma",
"email": "[email protected]"
}
Make sure the request includes an appropriate Content-Type header, normally application/json for a JSON payload. Postman generally adds this when JSON is selected in the raw body options.
Expected Response
{
"id": 1,
"name": "Aarav Sharma",
"email": "[email protected]"
}
The sample controller returns 201 Created when the resource is created successfully.
POST Request Test Checklist
- Confirm the endpoint returns the expected success status.
- Verify that the returned resource contains an identifier.
- Check that submitted values appear correctly in the response.
- Test missing fields and malformed JSON.
- Test invalid values after validation rules are implemented.
- Check whether duplicate records are allowed or rejected according to requirements.
9. Testing a PUT Request in Postman
PUT is typically used to replace or fully update a resource at a known URL. The exact behavior depends on the API contract.
Example Request
PUT http://localhost:8080/api/employees/1
Choose Body → raw → JSON and send the complete representation required by the API.
{
"name": "Aarav Sharma",
"email": "[email protected]"
}
In the sample controller, a successful update returns 200 OK. If the identifier does not exist, it returns 404 Not Found.
PUT Testing Checklist
- Verify that the correct record is updated.
- Confirm that the response contains the updated values.
- Check how the API handles omitted fields.
- Verify the expected behavior for a nonexistent identifier.
- Send a GET request after updating to confirm the stored state.
10. Testing a PATCH Request in Postman
PATCH is generally used to update selected fields rather than replacing the entire resource. The API must explicitly implement PATCH behavior; it is not automatically provided by the sample controller above.
Example Request
PATCH http://localhost:8080/api/employees/1
For an API that supports partial JSON updates, a request body might contain only the field to change:
{
"email": "[email protected]"
}
PATCH Testing Checklist
- Confirm that only the intended fields change.
- Verify that unspecified fields remain unchanged.
- Test invalid field names and invalid values.
- Check the behavior for a nonexistent resource.
- Confirm the documented status code and response format.
11. Testing a DELETE Request in Postman
DELETE is used to remove a resource or request its removal, according to the API design.
Example Request
DELETE http://localhost:8080/api/employees/1
The sample controller returns 204 No Content when the employee is successfully deleted. A subsequent GET request for that employee returns 404 Not Found.
DELETE Testing Checklist
- Confirm the expected success status code.
- Check whether the response body should be empty.
- Send a GET request afterward to verify deletion.
- Test deletion of a nonexistent identifier.
- Verify that unauthorized users cannot delete protected resources.
12. Understanding HTTP Status Codes
HTTP status codes communicate the result of an API request. The expected code should be based on the endpoint's documented contract rather than assumed to be the same for every API.
| Status Code |
Meaning |
Common Testing Scenario |
| 200 OK |
Request succeeded. |
Retrieving or updating a resource. |
| 201 Created |
A resource was created. |
Successful POST request. |
| 202 Accepted |
Request was accepted for processing. |
Asynchronous processing. |
| 204 No Content |
Request succeeded without a response body. |
Successful deletion. |
| 400 Bad Request |
Request is invalid or malformed. |
Invalid JSON or request parameters. |
| 401 Unauthorized |
Valid authentication is missing or unsuccessful. |
Missing or invalid credentials. |
| 403 Forbidden |
The caller is not permitted to perform the action. |
Insufficient permissions. |
| 404 Not Found |
The resource or endpoint cannot be found. |
Unknown resource identifier. |
| 405 Method Not Allowed |
The method is unsupported for the endpoint. |
Using an unsupported HTTP method. |
| 409 Conflict |
The request conflicts with the current resource state. |
Duplicate unique record. |
| 415 Unsupported Media Type |
The request media type is unsupported. |
Incorrect Content-Type. |
| 422 Unprocessable Content |
The content cannot be processed according to the API's rules. |
Semantic validation failure where this status is used. |
| 429 Too Many Requests |
The caller exceeded a rate limit. |
Rate-limiting tests. |
| 500 Internal Server Error |
The server encountered an unexpected error. |
Unexpected server-side failure. |
13. Working with Request Headers
HTTP headers carry metadata about a request or response. In Postman, headers can be entered through the Headers tab or configured automatically through other request settings.
| Header |
Purpose |
Example |
| Content-Type |
Indicates the format of the request body. |
application/json |
| Accept |
Indicates acceptable response formats. |
application/json |
| Authorization |
Provides credentials or a token. |
Bearer <token> |
| Cache-Control |
Provides caching directives. |
no-cache |
Example Header Configuration
Content-Type: application/json
Accept: application/json
Do not set a Content-Type that conflicts with the body format. For example, a JSON body should normally be sent as application/json, not as form-encoded data.
14. Testing Query Parameters and Path Variables
REST APIs commonly use query parameters for filtering, searching, sorting, and pagination. Path variables identify a specific resource.
Query Parameter Example
GET http://localhost:8080/api/products?category=books&page=0&size=10
In Postman, enter the parameters in the Params tab rather than manually assembling the URL. This makes the request easier to read and modify.
Path Variable Example
GET http://localhost:8080/api/employees/1
Here, 1 is the resource identifier passed to the controller through a path variable.
Test Cases
- Send valid query parameter values.
- Omit optional parameters and confirm default behavior.
- Test empty, negative, or out-of-range values where relevant.
- Test a nonexistent resource identifier.
- Verify that filters and pagination return the correct records.
15. Testing JSON Serialization and Deserialization
Serialization converts a Java object into a response representation, commonly JSON. Deserialization converts a JSON request body into a Java object. Spring Boot commonly uses Jackson for JSON processing when the appropriate web dependencies are present.
Example JSON Payload
{
"name": "Priya Mehta",
"email": "[email protected]"
}
What Should Be Verified?
- JSON property names match the API contract.
- String, numeric, Boolean, array, and nested object values have the expected types.
- Required properties are accepted when valid and rejected when invalid.
- Malformed JSON produces an appropriate client error response.
- Response JSON contains the documented fields.
- Sensitive fields, such as passwords, are not exposed in responses.
16. Testing Validation and Error Responses
Validation ensures that incoming data meets business and technical rules. For example, an employee name may be required, and an email field may need to contain a valid email address.
Example Spring Boot Validation Model
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotBlank;
public class EmployeeRequest {
@NotBlank(message = "Name is required")
private String name;
@NotBlank(message = "Email is required")
@Email(message = "Email must be valid")
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
For Spring Boot 3, validation commonly uses Jakarta Validation annotations and requires a compatible validation implementation, such as the Spring Boot validation starter.
Using Validation in a Controller
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/validation-demo")
public class ValidationController {
@PostMapping
public String create(
@Valid @RequestBody EmployeeRequest request) {
return "Employee request is valid";
}
}
Test Invalid Data in Postman
Send a POST request with the following body:
{
"name": "",
"email": "not-an-email"
}
Check that the request is rejected and that the API returns a useful error response. Depending on the application's exception handling, the response may contain validation messages and a status such as 400 Bad Request.
Error-Handling Scenarios
- Missing required fields.
- Invalid email or date formats.
- Malformed JSON.
- Invalid identifiers or query parameters.
- Resource not found.
- Authentication or authorization failure.
- Unexpected server exceptions.
Test the error response structure as well as the status code. A well-designed API should return a consistent, documented error format without exposing stack traces, internal class names, database credentials, or other sensitive information.
17. Writing Automated Tests in Postman
Postman supports JavaScript scripts that run after a response is received. Depending on the version of the interface, these are commonly found under Scripts → Post-response; older versions may label the area Tests. Tests can validate status codes, response data, headers, and other expectations.
Test 1: Verify the Status Code
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
Test 2: Verify JSON Content Type
pm.test("Response is JSON", function () {
pm.expect(
pm.response.headers.get("Content-Type")
).to.include("application/json");
});
Use this assertion when the endpoint is expected to return JSON. Some APIs may return other content types or additional parameters in the header.
Test 3: Validate a Response Property
pm.test("Employee response has a name", function () {
const response = pm.response.json();
pm.expect(response).to.have.property("name");
pm.expect(response.name).to.be.a("string");
});
Test 4: Validate the Response Time
pm.test("Response time is below 1000 ms", function () {
pm.expect(pm.response.responseTime).to.be.below(1000);
});
The threshold above is an example for practice, not a universal performance requirement. Real thresholds should reflect the application's service-level objectives and test environment.
Test 5: Verify an Employee Identifier
pm.test("Employee ID is present", function () {
const response = pm.response.json();
pm.expect(response.id).to.exist;
});
Test 6: Check an Error Response
pm.test("Missing employee returns 404", function () {
pm.response.to.have.status(404);
});
Attach this test to a request specifically designed to retrieve a nonexistent employee. If the API uses a different documented behavior, update the assertion to match that contract.
18. Using Variables in Postman
Variables allow developers to reuse values without repeatedly typing them into every request. They are useful for API base URLs, resource identifiers, access tokens, and test data. Postman variables are commonly referenced using double curly braces.
Example Variables
base_url = http://localhost:8080
employee_id = 1
Use them in a request like this:
GET {{base_url}}/api/employees/{{employee_id}}
Common Variable Scopes
| Scope |
Typical Use |
| Global |
Values shared broadly across a workspace. |
| Collection |
Values reused by requests in a collection. |
| Environment |
Configuration for development, testing, or staging environments. |
| Data |
Values supplied by a data file during a run. |
| Local |
Temporary values used during a script or run. |
Save an ID from a Response
After a successful POST request, the generated ID can be saved for a later request. Add this script to the POST request's Post-response area:
const response = pm.response.json();
pm.test("Employee creation succeeded", function () {
pm.expect(pm.response.code).to.be.oneOf([200, 201]);
});
if (response.id !== undefined) {
pm.environment.set("employee_id", response.id);
}
Choose the correct active environment and ensure the variable exists or can be created there. The following GET request can use {{employee_id}} to retrieve the newly created record.
19. Creating and Organizing Collections
A collection is a group of related API requests. Instead of managing every request separately, developers can organize endpoints by feature or workflow and run them together.
Example Collection Structure
Employee API Tests
|
|-- Create Employee (POST)
|-- Get All Employees (GET)
|-- Get Employee By ID (GET)
|-- Update Employee (PUT)
|-- Delete Employee (DELETE)
|-- Get Deleted Employee (GET - expected 404)
Benefits of Collections
- Keep related requests organized.
- Reuse scripts and configuration where appropriate.
- Support repeatable manual and automated testing.
- Make it easier to share API test scenarios with a team.
- Help validate complete workflows across multiple endpoints.
20. Using Environments for Different Servers
Applications often run in local, development, staging, and production environments. Environment variables allow the same collection to be reused with different base URLs and configuration values.
| Environment |
Example Base URL |
| Local |
http://localhost:8080 |
| Development |
https://dev-api.example.com |
| Staging |
https://staging-api.example.com |
The example domains are placeholders and must be replaced with valid environments that you are authorized to access.
Environment Setup
- Create an environment in Postman.
- Add a variable named
base_url.
- Set its value to the intended server URL.
- Select the environment before running requests.
- Use
{{base_url}} in request URLs.
- Verify the active environment before sending requests.
Do not accidentally run destructive requests against production. Keep credentials and other sensitive values out of shared examples and exported collections unless they are intentionally secured.
21. Testing Authentication and Authorization
Protected APIs may require users to authenticate before accessing resources. Postman supports common authentication configurations, including bearer tokens and Basic authentication, when these are supported by the API.
Bearer Token Example
Authorization: Bearer <access_token>
In Postman, open the Authorization tab, select Bearer Token, and enter the token in the designated field. Prefer the built-in authorization configuration over manually duplicating sensitive credentials across requests.
Authentication Test Cases
- Send a request without a token.
- Send a request with an invalid or expired token.
- Send a request with a valid token.
- Verify that users with insufficient permissions receive the expected response.
- Confirm that public endpoints remain accessible when intended.
- Check that sensitive information is not included in error messages.
Authentication and authorization failures are not always interchangeable. A typical API may return 401 for missing or invalid authentication and 403 when an authenticated caller lacks permission, but the actual contract should be verified.
22. Negative Testing and Edge Cases
Negative testing checks how the API behaves when requests contain invalid data or violate the application's rules. It is essential because a successful request alone does not prove that an API handles errors safely.
| Test Scenario |
Example |
What to Verify |
| Missing required value |
Name omitted from POST body. |
Validation error and appropriate status. |
| Malformed JSON |
Missing closing brace. |
Request is rejected without an unexpected server failure. |
| Invalid identifier |
GET with a nonnumeric ID. |
Consistent client error response. |
| Nonexistent record |
GET /api/employees/99999. |
Expected not-found behavior. |
| Unsupported method |
Use PATCH on an endpoint that does not implement it. |
Documented method handling. |
| Incorrect media type |
Send XML when only JSON is supported. |
Appropriate content-type handling. |
| Unauthorized operation |
Delete a protected record without credentials. |
Access is denied according to policy. |
| Boundary values |
Very long name or maximum page size. |
Validation and resource limits work correctly. |
23. Running a Collection as a Test Suite
Postman can run a collection's requests in sequence and display the results of its assertions. This helps teams repeat a set of API checks after code changes or before a release.
Basic Workflow
- Open the collection containing the API requests.
- Confirm that the required environment is selected.
- Review the request order and any dependencies.
- Ensure that test scripts have been added to the relevant requests.
- Open the collection runner using the available interface.
- Choose the appropriate environment and run settings.
- Run the collection and review passed and failed tests.
- Investigate failures, fix the underlying issue, and rerun the tests.
Why Request Order Matters
A workflow that creates an employee, retrieves it, updates it, and deletes it depends on the resource identifier generated during creation. Save that identifier to a variable and make later requests reference it. Ensure that the collection is designed to handle reruns without relying on stale or hard-coded IDs.
24. Common Postman Testing Problems and Solutions
| Problem |
Possible Cause |
Solution |
| Could not get response |
Server is stopped or URL is incorrect. |
Start the application and verify the host, port, and path. |
| Connection refused |
No service is listening on the requested port. |
Check application startup logs and port configuration. |
| 404 Not Found |
Incorrect route or missing resource. |
Check controller mappings and the resource identifier. |
| 400 Bad Request |
Invalid JSON, parameter conversion, or validation failure. |
Inspect the payload and error response. |
| 415 Unsupported Media Type |
Incorrect or missing Content-Type header. |
Set the correct media type for the body. |
| 401 Unauthorized |
Credentials are missing, invalid, or expired. |
Configure valid authentication credentials. |
| 403 Forbidden |
The user lacks the required permission. |
Check roles and authorization rules. |
| Variable unresolved |
Variable name is misspelled or the wrong environment is active. |
Verify variable names, values, and selected environment. |
| Assertion fails |
The actual response differs from the expected result. |
Inspect the response and adjust either the implementation or the test expectation. |
| Unexpected 500 response |
An unhandled server-side error occurred. |
Inspect application logs and exception handling. |
25. Best Practices for REST API Testing with Postman
- Use clear request names that explain the operation being tested.
- Group requests into collections based on API functionality.
- Use variables for base URLs, IDs, and reusable configuration values.
- Keep environment-specific settings separate from request definitions.
- Write assertions for status codes, response fields, and important headers.
- Test both successful and unsuccessful requests.
- Verify data changes by retrieving resources after create, update, or delete operations.
- Use representative test data and clean up resources created during testing.
- Keep tests independent where possible to reduce failures caused by execution order.
- Use explicit expectations instead of accepting any response as successful.
- Do not store real passwords, private keys, or access tokens in publicly shared collections.
- Never run destructive tests against a production system without explicit authorization and safeguards.
- Use realistic response-time thresholds based on the application's requirements.
- Document assumptions, required environment variables, and setup instructions.
- Use automated tests alongside unit, integration, and security testing rather than treating Postman as the only testing method.
26. Practical Exercise: Employee REST API Testing
Build a collection named Employee REST API Tests and use it to test the employee controller described earlier.
Exercise Tasks
- Send a GET request to retrieve all employees.
- Send a POST request to create an employee with a name and email.
- Verify the response status and returned employee data.
- Save the generated employee ID to an environment variable.
- Use the saved ID in a GET request to retrieve the employee.
- Send a PUT request to update the employee's details.
- Retrieve the employee again and verify the updated values.
- Send a DELETE request and verify the expected status.
- Attempt to retrieve the deleted employee and confirm the expected not-found behavior.
- Add post-response scripts to automate important assertions.
- Extend the application with validation and test invalid payloads.
- Record the results and investigate any failed assertions.
Sample Test Case Table
| Test Case ID |
Test Description |
Expected Result |
| TC01 |
Retrieve all employees. |
200 OK and a valid response body. |
| TC02 |
Create an employee with valid data. |
201 Created and returned employee details. |
| TC03 |
Retrieve an existing employee. |
200 OK with the correct identifier. |
| TC04 |
Retrieve a nonexistent employee. |
404 Not Found. |
| TC05 |
Update an existing employee. |
200 OK and updated values. |
| TC06 |
Delete an existing employee. |
204 No Content. |
| TC07 |
Retrieve an employee after deletion. |
404 Not Found. |
| TC08 |
Submit invalid data to a validated endpoint. |
Documented validation error. |
Note: These expected results correspond to the sample controller and validation examples when implemented as described. Other APIs may intentionally use different status codes or response formats.
27. Interview Questions and Answers
Q1. What is Postman?
Answer: Postman is a tool for developing, sending, inspecting, and testing API requests. It supports collections, environments, authentication configuration, and scripts for automating API checks.
Q2. Why is Postman used for REST API testing?
Answer: It allows developers and testers to validate endpoints independently of a frontend, inspect HTTP responses, test request payloads, and automate repeatable assertions.
Q3. What is the difference between GET and POST?
Answer: GET is generally used to retrieve resources, whereas POST is commonly used to submit data that creates a resource or triggers an operation.
Q4. What is the difference between PUT and PATCH?
Answer: PUT is commonly used for replacing or fully updating a resource, while PATCH is used for partial updates. Their exact semantics depend on the API contract.
Q5. What is the purpose of the Content-Type header?
Answer: Content-Type identifies the media type of the request body so the server can interpret the submitted data correctly.
Q6. What is the purpose of the Accept header?
Answer: Accept indicates which response media types the client can process, such as application/json.
Q7. What is a Postman collection?
Answer: A collection groups related requests and can include scripts and configuration that help organize and repeat API testing.
Q8. What are Postman environment variables?
Answer: They store reusable configuration values for a particular environment, such as a local server URL, a testing server URL, or a resource ID.
Q9. How can you validate an HTTP status code in Postman?
Answer: Add a post-response test such as pm.test("Status is 200", () => pm.response.to.have.status(200));.
Q10. How do you test a JSON response?
Answer: Parse the response using pm.response.json() and use assertions to check required properties, value types, and expected values.
Q11. What is negative testing?
Answer: Negative testing checks how an API responds to invalid input, missing data, incorrect authentication, unsupported methods, and other failure scenarios.
Q12. How do you test authentication?
Answer: Send requests with missing, invalid, and valid credentials, then verify that each result matches the API's authentication and authorization rules.
Q13. What is a 404 response?
Answer: HTTP 404 indicates that the requested resource or endpoint was not found.
Q14. What is the difference between 401 and 403?
Answer: A 401 response usually indicates missing or invalid authentication, whereas 403 generally indicates that the caller is not permitted to perform the operation.
Q15. Can Postman automate API tests?
Answer: Yes. Post-response scripts can assert expected results, and collections can run multiple requests as repeatable test suites.
28. Quick Revision
- Postman is used to send HTTP requests and test API responses.
- GET retrieves resources, POST commonly creates resources, PUT replaces or fully updates resources, PATCH partially updates resources, and DELETE requests removal.
- Headers provide request and response metadata.
- JSON bodies are commonly sent with Content-Type set to application/json.
- Status codes communicate the outcome of an HTTP request.
- Post-response scripts can validate status codes, response bodies, and headers.
- Variables reduce duplication and support reusable request workflows.
- Collections group related requests into test suites.
- Environments allow the same requests to target different servers.
- Negative testing checks invalid inputs, missing credentials, and failure scenarios.
- Never expose sensitive credentials or run destructive tests on systems without authorization.
29. Conclusion
Testing REST APIs using Postman is an essential practical skill for Advanced Java and Spring Boot developers. It helps verify that API endpoints accept valid requests, reject invalid inputs appropriately, return correct status codes, and provide reliable response data.
By combining manual request testing with JavaScript assertions, variables, environments, and collections, developers can create repeatable test workflows and detect API regressions earlier. Effective API testing should cover successful operations, negative scenarios, validation, authentication, response consistency, and application-specific requirements.
To learn more about Advanced Java and related backend development topics, visit JustAcademy's Advanced Java Training Course, explore the JustAcademy website, or register for a course demo.
30. Further Reading