Mandatory Field Validation
Introduction
Most APIs require certain fields to be present before processing a request. These fields are called mandatory fields or required fields because the API cannot complete the business operation safely without them. A user registration API usually requires a username, email, and password. An employee creation API may require a name and department. A payment API requires an account number, amount, and currency. An order API requires product ID and quantity. Without these fields, the API does not have enough information to perform the requested action correctly.
Mandatory Field Validation verifies that all required fields are present and contain acceptable values before the API processes the request. If a mandatory field is missing, empty, null, whitespace-only, incorrectly named, or invalid according to business rules, the API should reject the request with a clear validation error. It should not create incomplete records, update partial data, trigger downstream processing, or silently apply unsafe defaults.
This validation is one of the most common and important parts of API testing because missing required data can cause database integrity issues, business rule violations, downstream failures, and confusing user experiences. A backend service that accepts incomplete data may appear to work initially, but the bad data often causes defects later in reporting, search, notifications, integrations, billing, compliance, or customer support.
For API testers, Mandatory Field Validation is not limited to removing a property from a JSON request. Testers should also check empty strings, null values, whitespace-only strings, multiple missing fields, incorrect field names, optional fields, duplicate fields where applicable, and whether failed validation leaves the database unchanged. A strong mandatory field test proves both the error response and the absence of unintended side effects.
What Is Mandatory Field Validation?
Mandatory Field Validation verifies that all required fields are present and contain valid values before the API processes the request. The API contract defines which fields are required, which fields are optional, and what kind of values are acceptable. The server should enforce those rules regardless of what the user interface does.
A simple definition is this: Mandatory Field Validation ensures that all required fields are provided and contain acceptable values before an API request is processed. If any required field is missing or invalid, the API should return a validation error and stop processing the operation.
For example, if an employee API requires `name` and `department`, a request that contains only `department` should fail. A request that contains `name` as an empty string should usually fail. A request that contains `name` as null should fail. A request that contains `name` as three spaces should fail if the business expects a meaningful name.
Mandatory field validation is different from general format validation, but the two often work together. A field may be mandatory and also need a valid format. For example, email may be required during registration and must also follow an email format. Password may be required and must also satisfy password rules. Amount may be required and must also be numeric and greater than zero.
Why Mandatory Field Validation Is Important
Mandatory Field Validation ensures data completeness. APIs often create or update records that other systems depend on. If required fields are missing, the record may be unusable. An employee without a name, a payment without an amount, an order without quantity, or a patient record without date of birth can break downstream workflows.
It maintains database integrity. Databases may have not-null constraints, foreign key rules, unique constraints, and required columns. However, relying only on database errors is not good API design. The API should validate the request early and return a meaningful client-facing error instead of exposing database exceptions or allowing inconsistent data.
Mandatory field validation enforces business rules. Required fields are usually required for a reason. A payment needs an amount because money movement cannot happen without it. A registration request needs email because communication and account recovery depend on it. An employee needs a department because access, reporting, and workflow routing may depend on department.
It also improves application reliability. When incomplete requests are rejected early, downstream services receive cleaner data. This reduces defects in integrations, background jobs, analytics, audit logs, notifications, and reporting. Good validation prevents bad data from spreading through the system.
Validation Workflow
A typical mandatory field validation workflow starts when the API receives a request. The server validates required fields before performing the business operation. If all required fields are present and valid, the request continues. If any required field is missing or invalid, the API returns a validation error and stops processing.
API Request
|
Required Field Check
|
All Fields Present?
|
Yes -> Process Request
No -> Validation Error
This workflow should happen before database persistence, event publishing, payment processing, email sending, or downstream service calls. Validation should be an early gate. If validation happens after data is saved, the system may already be polluted by incomplete records.
When validation fails, the API should return a consistent error response. The response may include a general message, field-level errors, error codes, trace IDs, and documentation links depending on the API standard. The response should help clients fix the request without revealing internal implementation details.
Example API
Consider an employee creation endpoint. The API accepts name, department, and salary. In this example, `name` and `department` are required, while `salary` is optional.
POST /employees
Content-Type: application/json
{
"name": "John",
"department": "QA",
"salary": 60000
}
If `name` and `department` are present and valid, the API can create the employee. The optional salary field may be included or omitted. If salary is omitted, the API may store null, apply a default, or leave the value unset depending on business rules.
A valid request can omit the optional field while still satisfying mandatory validation.
{
"name": "John",
"department": "QA"
}
The expected response may be `201 Created` with the created employee details. The exact response depends on the API design, but the important point is that all required fields are present and valid.
Missing Mandatory Field
A missing mandatory field test removes one required field from the request. If `name` is required, the following request should fail because it includes department but not name.
{
"department": "QA"
}
The expected result is commonly `400 Bad Request`, although some APIs use `422 Unprocessable Entity` for validation failures. The response should clearly indicate that name is required.
400 Bad Request
{
"message": "Name is required"
}
The tester should verify that no employee record was created. A failed validation response is not enough if the database still contains a partial record. Mandatory field validation must protect both the API response and backend state.
Multiple Missing Fields
When multiple mandatory fields are missing, the API should return a clear validation response. Some APIs return all validation errors at once. Others return the first error only. Both approaches can be valid if documented, but returning all errors is usually more client-friendly because the caller can fix everything in one attempt.
{}
An example response may include an array of field-level errors.
{
"errors": [
"Name is required",
"Department is required"
]
}
The exact response format depends on API design. Testers should verify consistency. If one endpoint returns an `errors` array and another returns a single string for similar validation failures, the inconsistency may make client handling harder. API standards should define a common validation error structure.
Empty, Null, and Whitespace Values
Mandatory fields must usually contain meaningful values, not merely exist as JSON properties. An empty string should not satisfy a required field if the business rule expects an actual name. For example, `"name": ""` should usually be rejected.
{
"name": "",
"department": "QA"
}
Null values should also be tested. A field can be present but set to null. If the field is required, null should usually be rejected.
{
"name": null,
"department": "QA"
}
Whitespace-only values are another important case. A string containing spaces may technically be non-empty, but it does not contain meaningful business data. Applications should trim and validate whitespace-only values according to business rules.
{
"name": " ",
"department": "QA"
}
These cases often reveal weak validation. Some APIs only check whether the property exists, allowing empty or whitespace values to pass. Good mandatory field validation checks presence and meaning.
Missing JSON Property and Incorrect Field Names
A missing JSON property means the required field is not included in the request at all. For example, if `name` and `department` are required, a request containing only salary should fail.
{
"salary": 50000
}
Incorrect field names should also be tested. If the API expects `department`, a client might accidentally send `dept`. The API should not treat the incorrect property as valid unless aliases are explicitly supported. It should return a validation error for the missing required field.
{
"name": "John",
"dept": "QA"
}
This test is useful because misspelled fields are common in client integrations. The API should fail clearly rather than silently ignoring the wrong field and creating incomplete data.
Mandatory vs Optional Fields
Mandatory fields must be supplied for the request to succeed. Optional fields may be omitted without causing failure. The API specification should clearly identify which fields are mandatory and which are optional.
| Field | Required? |
|---|---|
| name | Yes |
| department | Yes |
| No | |
| phone | No |
Testing optional fields is part of mandatory validation. If a field is truly optional, omitting it should not fail the request. A common defect is treating optional fields as required in one endpoint but optional in another. Another defect is allowing a required field to be omitted because the backend applies an unsafe default.
Optional does not always mean unvalidated. If an optional field is provided, it may still need to follow format rules. For example, phone may be optional, but if supplied it should follow phone number validation. Email may be optional in an employee record, but if supplied it should be a valid email.
Required Fields in Different APIs
Different APIs have different required fields because each business operation needs different information. A login API commonly requires username and password. A registration API may require first name, last name, email, and password. An employee API may require name and department while allowing salary and phone to be optional.
A payment API usually requires account number, amount, and currency. A transfer API may also require source account, destination account, transfer date, and authentication context. An order API may require product ID, quantity, customer ID, shipping address, and payment method depending on the workflow.
Required fields can also vary by operation. A field required during creation may not be required during update. For example, employee name may be required when creating an employee but not required when partially updating only the department. Testers should understand the operation context before deciding expected behavior.
Required fields can also vary by user role, country, product type, account type, feature flag, or API version. Advanced APIs may have conditional mandatory fields, such as requiring tax ID only for business accounts or requiring guardian details only for minors.
Mandatory Field Validation in API Testing
QA engineers should verify missing fields, empty values, null values, whitespace values, incorrect field names, duplicate fields where applicable, error messages, status codes, response schema, and database integrity. Each case checks a different weakness in validation logic.
Missing fields confirm that required properties are enforced. Empty and whitespace values confirm that fields must contain meaningful content. Null values confirm that the API does not accept absence disguised as a present property. Incorrect field names confirm that clients must follow the contract. Multiple missing fields confirm how the API reports combined validation failures.
Database integrity is critical. A request that fails mandatory validation should not create or modify records. If a create request fails because name is missing, no employee should be inserted. If an update request fails because a required field is invalid, existing data should remain unchanged.
Authorization should still be considered. Mandatory validation does not replace authentication and authorization. Depending on security design, an unauthenticated request may fail with `401 Unauthorized` before field validation occurs. Testers should understand validation order and expected precedence.
Example Test Cases
A positive mandatory field test sends all required fields and expects success, such as `201 Created` for a create request. A missing name test omits `name` and expects validation failure. A missing department test omits `department` and expects validation failure. A missing multiple fields test omits both name and department and expects a validation response.
An empty name test sends `"name": ""` and expects rejection. A null name test sends `"name": null` and expects rejection. A whitespace name test sends `"name": " "` and expects rejection. An incorrect field name test sends `employeeName` when the API expects `name` and verifies that the required `name` field is still considered missing.
Optional field tests should prove that optional fields can be omitted. For example, if salary is optional, a request containing only name and department should succeed. If salary is included with an invalid type, that becomes optional-field format validation, not mandatory validation.
Validation Checklist
For every mandatory field scenario, verify the correct status code, validation message, error response structure, required field enforcement, optional field behavior, unchanged database state after failure, and business rule consistency. The response should be clear enough for API clients to fix the request.
The error response should identify the field when possible. A generic message such as `Invalid request` may be technically correct but less helpful. A field-level message such as `name is required` is easier for clients and testers to understand. However, error messages should not expose internal class names, database columns, stack traces, or implementation details.
Validation should be consistent across endpoints. If missing `name` returns `400 Bad Request` in one endpoint and `500 Internal Server Error` in another, the API is inconsistent. If one endpoint returns an array of field errors and another returns a plain string, client error handling becomes harder. Consistency is part of quality.
REST Assured Example
REST Assured can automate mandatory field validation in Java. A simple missing-name test sends only department and expects validation failure.
given()
.contentType("application/json")
.body("""
{
"department": "QA"
}
""")
.when()
.post("/employees")
.then()
.statusCode(400);
A stronger test should also validate the error message and field name. It may verify that no employee was created by searching for the attempted data or checking a follow-up API response. If the API returns a structured error body, assertions should check that structure.
For data-driven testing, the same REST Assured test can run with multiple payloads: missing name, missing department, null name, empty name, whitespace name, and missing multiple fields. Each dataset can include expected status and expected message.
Postman Example
Postman can be used to test missing required fields manually or through collection runner. Test scenarios may include missing required field, empty value, null value, whitespace value, missing multiple fields, and optional field omitted.
Postman test scripts should verify status code, error message, response schema, and response time. If the API returns field-level errors, scripts can check that the expected field is included in the error response. Environment or collection variables can store test data for repeated execution.
For API teams that use Postman in CI through Newman, mandatory field scenarios can be part of the automated regression suite. This is useful because validation rules frequently change when APIs evolve.
Karate Example
Karate can express mandatory field validation clearly. A missing name scenario can send a request containing only department and verify the error status.
Given request
"""
{
"department": "QA"
}
"""
When method POST
Then status 400
Karate scenario outlines are useful for multiple required-field cases. A table can include request payload, expected status, and expected error message. This keeps the test compact while still covering many validation scenarios.
Real-World Examples
In banking, account number and amount are mandatory for many payment or transfer operations. If amount is missing, the API should reject the request before any transaction is created. The test should verify that no debit, credit, or pending transaction is recorded.
In healthcare, patient name and date of birth may be required for patient registration. Missing patient name should produce a validation error. Because healthcare data is sensitive and regulated, the API should not create incomplete patient records that could later be confused with real records.
In e-commerce, product ID and quantity are required for adding an item to an order. Missing quantity should fail validation because the system cannot calculate inventory reduction or order total. The cart or order should remain unchanged after the failed request.
In employee management, name and department may be required. Missing department should fail validation because department affects reporting, access control, workflow routing, and organizational structure.
Best Practices
Clearly document required fields in the API specification. Documentation should identify required fields, optional fields, conditional fields, default values, validation rules, and expected error responses. Testers should not have to infer required fields by trial and error.
Validate required fields on the server. Client-side validation in a web or mobile app is helpful for user experience, but it is not enough. APIs can be called directly by scripts, integrations, mobile clients, or attackers. Backend validation must enforce required fields independently.
Return meaningful validation messages. A good message identifies the missing or invalid field and helps the client fix the request. Keep messages safe and avoid implementation details. Use consistent error structures across APIs.
Reject null, empty, whitespace-only, and invalid required values according to business rules. Do not check only for property presence. A required field should contain meaningful data. Trim strings where appropriate before validation, or clearly define how whitespace is handled.
Ensure failed validation does not modify data. Validation should happen before persistence, event publishing, or downstream calls. Automate mandatory field validation tests because required-field defects are common and can easily reappear during API changes.
Common Mistakes
One common mistake is validating only missing fields. Testers should also test empty strings, null values, and whitespace-only values. Many APIs catch missing properties but accidentally accept empty values.
Another mistake is returning generic errors. A response such as `Bad request` may not be enough for clients to fix the problem. Field-level errors are usually better. At the same time, error responses should not expose stack traces, SQL messages, file paths, or internal validation class names.
Allowing invalid required values is a common API defect. A field may be present but meaningless. Required fields should contain valid, meaningful data, not placeholders that break business logic later.
Updating the database before validation is a serious problem. If incomplete data is saved before validation fails, the API can leave partial records behind. Validation should be completed before data is persisted.
Ignoring optional fields is another testing gap. Optional fields should be safely omitted. If the API fails when an optional field is absent, the implementation does not match the contract. If an optional field is supplied, it should still be validated according to its own rules.
Common HTTP Status Codes
Successful requests with all mandatory fields may return `200 OK` or `201 Created`, depending on the operation. Missing required fields commonly return `400 Bad Request`. Some APIs use `422 Unprocessable Entity` when the request syntax is valid but validation fails.
| Scenario | Status Code |
|---|---|
| Successful request | 200 OK or 201 Created |
| Missing required field | 400 Bad Request |
| Validation failure where used | 422 Unprocessable Entity |
The API specification should define which code is expected. Testers should follow the documented standard and report inconsistent behavior. If one endpoint returns `400` and another returns `422` for the same type of validation failure without explanation, that inconsistency should be reviewed.
Mandatory Field Validation Checklist
For each endpoint, identify all required fields and optional fields. For each required field, test the valid case, missing property, null value, empty string, whitespace-only value, incorrect field name, and invalid value where applicable. If multiple fields are required, test missing multiple fields and verify how the API reports combined errors.
For every validation failure, verify status code, response body, field-level message, response schema, headers where relevant, unchanged database state, and no downstream side effects. If the request is a create operation, confirm that no record is created. If it is an update operation, confirm that existing data remains unchanged.
For optional fields, verify that omitting the field does not fail the request. If the optional field is supplied, verify that it follows its own validation rules. If conditional required fields exist, test each condition clearly.
Advanced Scenarios
Some APIs have conditional mandatory fields. For example, `companyName` may be required only when account type is business. `guardianName` may be required only when patient age is below a certain limit. `routingNumber` may be required only for a bank transfer. These scenarios need business-aware validation tests.
Some APIs support partial updates. In a `PATCH` request, not every create-time mandatory field must be supplied because the operation modifies only selected fields. Testers should distinguish create validation from update validation. A missing `name` may fail during create but be acceptable during a department-only patch.
Some APIs apply defaults. Defaults should be intentional and documented. If a mandatory field is missing, applying a default may be valid in some cases, but it can also hide client errors. Testers should verify whether defaults are allowed and whether they create correct business behavior.
Conditional Required Fields
Conditional required fields deserve special attention because they are easy to miss in basic validation testing. A field may be optional in one scenario and mandatory in another. For example, `taxId` may be required for a business customer but optional for an individual customer. `state` may be required for one country but not for another. `approvalReason` may be required only when a request is rejected. These rules cannot be tested by simply removing fields from a default payload.
To test conditional validation, first identify the controlling field and the dependent field. Then test both sides of the rule. If account type is business, omit `companyName` and expect a validation error. If account type is individual, omit `companyName` and expect success if the field is truly optional. This proves that the API enforces the condition accurately rather than always requiring or always ignoring the field.
Conditional rules should also be tested during updates. If changing account type from individual to business makes `companyName` required, the update should fail unless the dependent field is supplied. If changing back to individual makes the field optional, the API should follow the documented behavior for existing company data. These details matter because conditional validation often affects real business workflows.
Interview Questions
A common interview question is: what is Mandatory Field Validation? A strong answer is that Mandatory Field Validation ensures all required fields are present and contain valid values before an API request is processed.
Another question is: why is Mandatory Field Validation important? It prevents incomplete or invalid data from entering the system, enforces business rules, protects database integrity, and reduces downstream failures.
Interviewers may ask what API testers should verify. Good answers include missing fields, empty values, null values, whitespace values, incorrect field names, error messages, status codes, response schema, optional field behavior, and database integrity.
If asked about mandatory versus optional fields, explain that mandatory fields must be supplied for the request to succeed, while optional fields may be omitted without affecting successful processing. If optional fields are supplied, they may still need validation.
If asked which HTTP status code is commonly returned for missing required fields, answer that `400 Bad Request` is common, although some APIs use `422 Unprocessable Entity` for validation failures depending on the API standard.
Interview-Ready Explanation
Mandatory Field Validation is the process of verifying that all required fields in an API request are present and contain valid values before the request is processed. If a mandatory field is missing, null, empty, whitespace-only, incorrectly named, or otherwise invalid according to business rules, the API should reject the request with an appropriate validation error.
During API testing, testers should verify missing required fields, null values, empty strings, whitespace-only values, multiple missing fields, optional field omission, conditional required fields, and incorrect field names. They should confirm that the API returns the correct HTTP status code, meaningful validation messages, a consistent error response structure, and does not create or modify any data after validation failures.
This validation is important because it prevents incomplete data from entering the system, protects database integrity, enforces business rules, and avoids downstream errors. Mandatory Field Validation is one of the most important parts of negative API testing and functional API validation.
Key Takeaway
Mandatory Field Validation ensures that an API receives the minimum required information before processing a request. Required fields must be present and meaningful, not missing, null, empty, or whitespace-only unless the API explicitly allows such values.
For practical API testing, validate every required field in multiple ways. Check missing properties, empty values, nulls, whitespace, incorrect names, multiple missing fields, optional field behavior, error response consistency, and unchanged backend state. Strong mandatory field validation prevents incomplete records and protects the reliability of the entire system.