Optional vs Mandatory Fields

Introduction

Every API request and response contains fields. These fields may also be called properties, attributes, parameters, or members, depending on the team and documentation style. Some fields are essential for the API to process a request or represent a response correctly. Other fields provide extra information and may appear only when that information is available. Understanding the difference between optional and mandatory fields is one of the most important foundations of API testing.

A user registration API usually requires an email and password because an account cannot be created without them. A middle name may be optional because many users do not have one or may not want to provide it. A shipping address may be mandatory for a physical product but optional for a digital download. A coupon code may be optional during checkout. A payment card number may become mandatory only when the selected payment type is credit card. These rules are not simply technical details; they represent business behavior.

When optional and mandatory fields are handled incorrectly, APIs become unreliable. If a mandatory field is not validated, incomplete records may be created. If an optional field is treated as mandatory, valid requests may be rejected. If a response omits a field that the contract says must always exist, client applications may fail. If null values, empty strings, missing fields, and conditional requirements are not defined clearly, testers and developers will interpret the API differently.

This tutorial explains optional and mandatory fields from a practical API testing perspective. It covers required fields, optional fields, missing fields, null values, empty values, conditional mandatory fields, request validation, response validation, schema validation, OpenAPI contracts, REST Assured examples, Postman examples, Karate examples, real-world scenarios, best practices, common mistakes, and interview-ready explanations.

What Are Mandatory Fields?

A mandatory field, also called a required field, is a field that must be present in an API request or response. If the field is required in a request and it is missing, the API should reject the request with a clear validation error. If the field is required in a response and it is missing, the API response does not match the contract and should be treated as a defect.

In simple terms, mandatory fields are fields that must always be provided because they are essential for processing the request or representing the resource. For example, a create user request usually needs a name or email. A payment request needs amount and currency. An order request needs product ID and quantity. A login request needs username and password.

Mandatory does not always mean the field can contain any value. A mandatory string may need to be non-empty. A mandatory number may need to be greater than zero. A mandatory email may need a valid email format. A mandatory object may need required child fields. A mandatory array may need at least one item. API testing should validate both presence and acceptable value rules.

What Are Optional Fields?

An optional field is a field that may or may not be present in a request or response. The API should continue to function correctly when the optional field is omitted, unless a specific business rule makes the field mandatory under certain conditions. Optional fields provide additional information, but they are not required for every scenario.

In simple terms, optional fields are fields that are not required for every request or response. A user profile may optionally contain middle name, nickname, secondary phone number, profile picture, or referral code. A product response may optionally contain discount, rating, warranty information, or promotional labels. A payment request may optionally contain remarks or reference information.

Optional does not mean uncontrolled. If an optional field is present, it should still follow the correct data type, format, length, and business rules. For example, an optional phone number can be omitted, but if it is provided, it should follow the expected phone format. An optional discount code can be absent, but if it is sent, it should be valid or rejected with a meaningful error.

Mandatory Field Example

Consider a user creation API where the documentation states that name and email are mandatory fields:

POST /users

{
  "name": "John",
  "email": "john@example.com"
}

This request contains both mandatory fields, so the API can validate the values and process the request. If the values are valid and no business rule fails, the API may create the user and return a success response.

Now consider a request where email is missing:

{
  "name": "John"
}

If email is mandatory, the expected response should be a validation error, commonly 400 Bad Request, with a message such as:

{
  "message": "Email is required"
}

This behavior is correct because the API rejects an incomplete request before creating invalid data. A tester should verify that the status code, error message, error code, and error body structure match the API contract.

Optional Field Example

Now consider the same user request with an optional field:

{
  "name": "John",
  "email": "john@example.com",
  "middleName": "David"
}

Here, middleName is optional. The request should also be valid without it:

{
  "name": "John",
  "email": "john@example.com"
}

If the API rejects the second request only because middle name is missing, then either the implementation is wrong or the documentation is wrong. Optional fields should not block normal API processing when omitted.

However, if an optional field is present, it still needs validation. If middleName has a maximum length of 50 characters, sending 500 characters should trigger validation. Optional means not always required; it does not mean ignored or unvalidated.

Mandatory vs Optional Fields

The key difference is that mandatory fields must be present, while optional fields may be omitted. Mandatory fields are required for business logic, identity, processing, calculation, or representation. Optional fields add extra context but are not required for every use case.

A mandatory field usually has strong validation rules. If missing, the API should return an error. If empty, null, or invalid, the API should respond according to the contract. An optional field should be handled gracefully when absent. When present, it should still be validated for type, format, and business meaning.

For testers, the difference drives test design. Mandatory fields require missing-field tests, null tests, empty-value tests, invalid-type tests, boundary tests, and valid-value tests. Optional fields require omitted-field tests, present-field tests, null-if-supported tests, empty-value tests, invalid-value tests, and valid-value tests. Both categories matter.

Real Examples by Domain

In user registration, email and password are typically mandatory. Phone number, referral code, middle name, and profile image are usually optional. A registration API should reject missing email or password, but it should not reject a request only because referral code is absent.

In a product API, product name and price are usually mandatory. Description, discount, rating, tags, and images may be optional depending on the business model. A create product endpoint should not accept a missing product name. At the same time, it should allow a product to be created without a rating if the product has not received reviews yet.

In a banking API, account number and amount are usually mandatory for a transfer. Remarks or reference number may be optional. In an employee API, employee ID and employee name are usually mandatory, while nickname and secondary phone number may be optional. In each domain, field requirements come from business rules, not arbitrary technical preference.

Optional Field with Null

An optional field may be omitted, but it may also be sent with a null value if the API supports null. These two cases are different. Consider this payload:

{
  "middleName": null
}

This payload includes the middleName field, but its value is null. Now compare it with this payload:

{
  "name": "John"
}

In the second payload, no middleName field exists. Some APIs treat these cases the same, while others treat them differently. In update requests, this distinction becomes very important. A missing field may mean leave the existing value unchanged. A null field may mean clear the existing value. An empty string may mean store a blank value.

Testers should verify how optional fields behave when omitted, sent as null, sent as an empty string, and sent with a valid value. These cases should be documented clearly because client teams need predictable behavior.

Missing Field vs Null Field vs Empty Value

A missing field is not included in the JSON document. A null field is included but has the value null. An empty value may be an empty string, empty array, or empty object depending on the field type. These cases are not the same, and APIs should not treat them accidentally.

{
}

The object above has no fields. The next payload contains a field with a null value:

{
  "middleName": null
}

The next payload contains a field with an empty string:

{
  "middleName": ""
}

For a required field, all three may be invalid. For an optional field, all three may be valid or only some may be valid. For an update endpoint, missing may mean no change, null may mean remove the value, and empty string may mean set it to blank. Good API testing covers these differences instead of assuming they are equivalent.

Conditional Mandatory Fields

Some fields are optional in general but become mandatory when another field has a specific value. These are conditional mandatory fields. They are common in real business workflows.

{
  "paymentType": "CreditCard"
}

If the payment type is credit card, then card number, CVV, and expiry date may become mandatory. If the payment type is cash on delivery, those fields may not be required. Similarly, if delivery type is home delivery, address may be mandatory. If delivery type is pickup, address may be optional or not allowed.

{
  "deliveryType": "Home"
}

Conditional rules are important because they connect field validation to business logic. A simple required-field schema may not express every conditional rule unless advanced schema features are used. Testers should create scenario-based tests for each condition, including valid combinations and invalid combinations.

Required Fields in API Responses

Mandatory fields are not limited to requests. API responses also have required fields. If the response contract says a user response must include id and name, then those fields should always be present in successful responses.

{
  "id": 101,
  "name": "John",
  "email": "john@example.com"
}

If the response returns only this:

{
  "name": "John"
}

and id is documented as required, the response is defective. Client applications may depend on the ID for navigation, updates, deletes, links, caching, or display. Missing required response fields can be just as harmful as accepting invalid request fields.

Response validation should check required fields, data types, nullable rules, optional fields, and sensitive field exposure. A response should not omit required fields silently, and it should not include confidential fields such as passwords or internal secrets.

Field Validation in API Testing

Field validation confirms that mandatory and optional fields behave according to the API specification. For mandatory fields, testers should verify presence, correct data type, correct value, non-empty rules, format rules, length rules, and business validation. For optional fields, testers should verify that the field can be omitted, can contain valid values, can be null if supported, can be empty if supported, and does not break API behavior when absent.

A request may include a valid email but omit a mandatory name. The expected result should be a clear validation error. Another request may include all mandatory fields and omit optional middle name. The expected result should be success. Another request may include an optional field with an invalid value. The expected result should depend on the contract, but the API should not ignore invalid optional data if that field affects stored information.

Testers should also validate response fields. Required response fields should exist every time. Optional response fields should appear only when appropriate. If optional fields are absent, the client should still receive a valid structure. If optional fields are present, they should use correct data types and values.

Test Cases for Mandatory Fields

Mandatory fields need negative and positive test coverage. A positive test confirms that a request succeeds when all required fields are present with valid values. Negative tests confirm that the API rejects missing, null, empty, invalid, or wrongly typed required fields.

For a mandatory name field, useful tests include missing name, empty name, null name, name with only spaces, name longer than maximum length, name with unsupported characters if restrictions exist, and valid name. For a mandatory amount field, tests may include missing amount, null amount, zero amount, negative amount, decimal precision, maximum amount, and string instead of number.

Mandatory field validation should also test error messages. The response should identify the problematic field and explain the issue clearly. A vague message such as Invalid request may be less useful than Name is required or Amount must be greater than zero.

Test Cases for Optional Fields

Optional fields require a different style of testing. The first test is usually omission: the request should work when the optional field is not present. The second test is presence: the request should work when the optional field is present with a valid value. Additional tests cover null, empty values, invalid values, wrong data types, maximum length, and business constraints.

For an optional referral code, testers can send no referral code, a valid referral code, an invalid referral code, an expired referral code, an empty referral code, and a null referral code. The API should process each case according to business rules. If invalid referral code should reject the request, verify the error. If it should ignore the discount, verify the response and calculation.

Optional fields should never be ignored blindly. If optional data is accepted, it can still affect downstream behavior, database storage, notifications, reporting, and UI display. A good test confirms both immediate response behavior and important side effects where relevant.

Example Validation Flow

Suppose a create user API requires name and email. A test sends this request:

{
  "email": "john@example.com"
}

Because name is mandatory, the expected response may be:

400 Bad Request

{
  "message": "Name is required"
}

The validation should not stop at checking status code 400. It should also check that the error response body is valid JSON, the message is meaningful, the correct field is identified, and no user is created. For stronger validation, the test can query the user list or database in a controlled test environment to ensure no invalid record was stored.

For the optional field case, send the same request with all mandatory fields but without optional fields. The API should process it successfully. Then send optional fields with valid values and verify they are stored or returned correctly if that is part of the contract.

REST Assured Example

REST Assured can validate missing mandatory field behavior like this:

given()
  .contentType("application/json")
  .body(requestBody)
.when()
  .post("/users")
.then()
  .statusCode(400)
  .body("message", equalTo("Name is required"));

This verifies that the API rejects the request and returns the expected validation message. A more complete test may also verify an error code, field name, timestamp, and validation details array if the API uses a structured error format.

REST Assured can also validate response required fields. For example, after creating a user, the test can verify that id, name, and email exist and have correct data types. For schema-level validation, REST Assured can use JSON Schema validators.

Postman Example

Postman can validate mandatory field errors in the Tests tab:

pm.test("Missing name returns validation error", function () {
  pm.expect(pm.response.code).to.eql(400);
  pm.expect(pm.response.json().message).to.eql("Name is required");
});

For optional field omission, Postman can send a request without the optional field and verify success. For response validation, Postman can check that required fields exist:

pm.test("Required fields exist", function () {
  const body = pm.response.json();
  pm.expect(body).to.have.property("id");
  pm.expect(body).to.have.property("name");
});

Postman is useful for exploring field rules manually, and Newman can run the same collection in CI. When many required fields exist, schema validation is usually cleaner than writing many individual field assertions.

Karate Example

Karate can validate missing mandatory field behavior concisely:

Then status 400
And match response.message == 'Name is required'

It can also validate response structure and data types:

Then match response.id == '#number'
And match response.name == '#string'
And match response.email == '#string'

Karate is useful for API testing because the request, response, and validation rules remain readable. Optional field scenarios can be expressed clearly by sending payloads with omitted fields, null values, and valid values.

JSON Schema Validation

JSON Schema defines mandatory fields using the required keyword. For example:

{
  "required": [
    "name",
    "email"
  ]
}

If either field is missing, schema validation fails. JSON Schema can also define data types, minimum and maximum values, string lengths, enums, arrays, nested objects, nullable behavior, and additional properties. This makes it powerful for API contract validation.

However, schema validation should be combined with scenario-based tests. A schema can say that cardNumber is required, but conditional logic such as card number required only when payment type is credit card may need more detailed rules or separate business tests. Testers should understand what the schema covers and what still needs explicit scenario validation.

OpenAPI and Field Requirements

OpenAPI specifications are commonly used to document request and response contracts. They can define required fields, optional fields, field types, examples, formats, enum values, nullable rules, request bodies, response schemas, and error structures. When OpenAPI is accurate, testers can use it as a reliable source for field validation.

OpenAPI helps reduce ambiguity. Instead of relying on verbal assumptions, the team can see whether email is required, whether phone is optional, whether middleName can be null, and whether orders should be an array. Automated tools can also validate responses against the OpenAPI contract.

If implementation and OpenAPI do not match, testers should raise the difference. Sometimes the code is wrong. Sometimes the documentation is outdated. Either way, the mismatch creates risk for API consumers and should be resolved.

Validation Checklist

A practical validation checklist includes required fields exist, optional fields behave correctly when omitted, correct data types, null handling, empty values, conditional mandatory fields, required response fields, schema compliance, business rules, error messages, unsupported fields, extra fields, and security-sensitive fields.

For each mandatory request field, test valid value, missing field, null value, empty value, wrong data type, invalid format, and boundary conditions. For each optional request field, test omitted, valid value, null if supported, empty if supported, invalid value, and wrong data type. For response fields, verify required fields are always present and optional fields follow documented behavior.

This checklist should be adapted to risk. A payment API needs stronger validation than a simple preference API. A public API needs stricter contract behavior than an internal prototype. Critical workflows deserve explicit tests for field requirements.

Real-World Examples

In a registration API, email and password are mandatory because the account cannot be created without them. Referral code may be optional because it affects promotion tracking but not basic account creation. Tests should verify missing email, missing password, invalid email, weak password, omitted referral code, valid referral code, and invalid referral code.

In a payment API, amount and currency are mandatory because payment cannot be processed without them. Remarks may be optional. If payment method is credit card, card details may become mandatory. If payment method is wallet, wallet ID may become mandatory. This makes conditional validation important.

In an order API, product ID and quantity are mandatory. Coupon code may be optional. Shipping address may be mandatory for physical products and not required for digital products. In a login API, username and password are mandatory, while remember me may be optional. Each example shows that field requirements depend on business context.

Best Practices

Clearly document required and optional fields in the API specification. Validate all mandatory fields before processing requests. Support omission of optional fields without causing failures. Use conditional mandatory fields only when required by business rules. Validate both request and response payloads. Use JSON Schema or OpenAPI to define required fields. Return meaningful validation messages when mandatory fields are missing.

Do not rely only on happy-path tests. Missing required fields, null values, empty values, wrong data types, and invalid optional values are common sources of defects. Use controlled test data so validation results are predictable. Keep negative tests clear and focused on one field or one business rule when possible.

Maintain consistency across endpoints. If one endpoint returns empty arrays for missing collections, related endpoints should not randomly return null. If one endpoint uses email as required, related create and update endpoints should document how email behaves consistently. Consistency reduces client bugs and test confusion.

Common Mistakes

A common mistake is treating optional fields as mandatory. If documentation marks a field as optional, the API should not reject requests that omit it. If the implementation rejects the request, the documentation or implementation must be corrected.

Another mistake is ignoring required fields in responses. Mandatory response fields should always be present. If a field such as ID is required but missing, client applications may fail even though the server returned 200 OK.

Confusing null with missing fields is another frequent issue. A field with null exists but has no assigned value. A missing field does not exist in the JSON document. Empty string is a third case. These differences should be tested, especially in create and update requests.

Ignoring conditional requirements is also risky. If payment type, delivery type, customer type, account type, country, or product type changes which fields are required, those rules need direct tests. Otherwise, important business defects can remain hidden.

Interview Questions

A common interview question is: what is a mandatory field? A strong answer is that a mandatory field is a field that must be present in an API request or response because it is essential for processing or representing the resource. If a mandatory request field is missing, the API should return a validation error.

Another question is: what is an optional field? An optional field is a field that may be omitted without affecting normal API processing, unless a specific business rule makes it conditionally mandatory. If an optional field is present, it should still be validated.

Interviewers may ask the difference between a missing field and a null field. A missing field is not included in the JSON document. A null field exists but has no assigned value. An empty string is different again because the field exists and contains a string with no characters.

They may also ask what testers should validate. A strong answer includes required fields, optional fields, missing fields, null values, empty values, invalid values, wrong data types, conditional mandatory fields, response field requirements, schema compliance, business rules, and clear error messages.

Interview-Ready Explanation

Mandatory fields are required fields that must be present in an API request or response because they are essential for processing the request or representing the resource. If a mandatory request field is missing, null, empty, or invalid, the API should typically return a validation error such as 400 Bad Request with a meaningful message. If a mandatory response field is missing, the response does not match the API contract.

Optional fields are fields that may or may not be included. The API should continue to function correctly when optional fields are omitted, unless business rules make them conditionally mandatory. If an optional field is provided, it should still be validated for data type, format, length, and business meaning. Optional does not mean ignored.

During API testing, testers validate the presence of mandatory fields, verify optional fields when present and absent, test missing fields, null values, empty values, invalid values, wrong data types, conditional requirements, required response fields, and schema compliance. The goal is to ensure that the API follows the specification, protects data integrity, handles valid and invalid payloads predictably, and gives client applications a stable contract.

Key Takeaway

Optional and mandatory fields define how an API expects data to be sent and returned. Mandatory fields are required for processing or representation. Optional fields provide additional information and may be omitted. Both types must be validated carefully because incorrect field handling can create broken requests, incomplete responses, data quality issues, and client application failures.

For API testers, the practical rule is to test presence, absence, null, empty, type, value, and condition. A good API accepts valid required data, rejects missing mandatory data, handles omitted optional fields gracefully, validates optional fields when present, follows conditional business rules, and returns required response fields consistently. Strong field validation is one of the clearest signs of mature API testing.