Request Body

Introduction

Many API requests need to send data from the client to the server. A user registration request sends user details. A login request sends credentials. An order placement request sends product IDs, quantities, address information, and payment references. An employee update request sends changed employee data. The actual data sent as part of the HTTP request is called the request body, also known as the request payload.

The request body is different from the URL, path parameters, query parameters, and request headers. The URL identifies where the request is going. Path parameters identify specific resources. Query parameters filter or customize the request. Headers describe metadata such as authentication, content type, and expected response format. The request body contains the business data the server needs to create, update, replace, or process a resource.

Request bodies are especially common with POST, PUT, and PATCH requests. POST usually sends data to create a new resource or submit an operation. PUT sends a complete replacement representation for an existing resource. PATCH sends partial changes. Some APIs may also accept a body with DELETE, although that is less common and should be documented clearly. GET requests typically do not use a request body in normal REST API design.

For API testers, request body validation is one of the most important areas of API testing. Most business rules are expressed through request data. Required fields, data types, string lengths, numeric ranges, enum values, nested objects, arrays, duplicate values, null handling, invalid JSON, security payloads, and business validations all appear in the request body. A strong API tester must know how to design both positive and negative request body scenarios.

What Is a Request Body?

A request body is the data sent by the client to the server as part of an HTTP request. It contains the information required to create, update, replace, or process a resource. In a REST API, the request body is commonly formatted as JSON, but it can also be XML, form data, multipart form data, plain text, binary content, or another format supported by the API contract.

For example, a request to create a user may send this JSON body:

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

The server reads this payload, validates it, applies business rules, creates the user, and returns a response. If the email is missing or invalid, the server should return a validation error. If the Content-Type header does not match the body format, the server may not parse the payload correctly.

A simple definition is this: a request body is the actual data or payload sent from the client to the server in an HTTP request.

Why a Request Body Is Needed

Many API operations require input data that is too complex or too sensitive to place in a URL. User registration requires username, password, email, address, and profile information. Order creation requires products, quantities, shipping method, payment method, and customer information. Product creation requires name, price, category, inventory, and attributes. These values belong in the request body.

Sending complex data through the request body keeps the URL focused on resource identity. A clean request such as POST /users with a JSON body is easier to understand than a long URL such as /createUser?name=John&city=Chicago&email=john@example.com. Query parameters are useful for filtering and options, but request bodies are better for complex structured data.

Request bodies also support nested structures. A user can have an address object. An order can have an array of line items. A payment request can contain billing details and tokenized payment information. This structure is hard to represent cleanly in a query string but natural in JSON or XML.

For testing, this means request body coverage must include realistic business data. Tests should not only send the smallest possible payload. They should also send valid complete payloads, optional fields, nested data, arrays, invalid values, and business edge cases that resemble real client behavior.

HTTP Request Structure

An HTTP request has several parts. It begins with a request line that includes the method and path. Then it includes request headers. A blank line separates the headers from the optional body. The request body appears after that blank line when the method and API contract allow one.

POST /users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json

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

Everything below the blank line is the request body. The Content-Type header tells the server that the body is JSON. If the same body is sent without Content-Type, some servers may reject it or fail to parse it. Headers and body work together, so request body testing should also include header validation.

In API tools such as Postman, the body is entered separately from headers. In automation frameworks such as REST Assured or Karate, the body is passed through request methods. Regardless of the tool, the HTTP structure is the same.

Which HTTP Methods Use a Request Body?

POST, PUT, and PATCH commonly use request bodies. POST sends data to create a resource or submit a process. PUT sends a complete replacement representation of a resource. PATCH sends partial changes. These methods usually need a body because the server needs data to perform the operation.

GET usually does not use a request body. A GET request retrieves data, and request options are normally passed through path parameters, query parameters, and headers. Some systems technically allow GET bodies, but they are not widely supported or recommended in common REST practice. HEAD does not return a response body and typically does not use a request body. OPTIONS usually does not need a body for common API usage.

DELETE usually does not use a request body, although some APIs support it for special cases such as deletion reasons or bulk deletion criteria. If DELETE bodies are used, the behavior must be documented clearly because client libraries, proxies, and tools may handle them inconsistently.

HTTP Method Request Body Usage
GETUsually no
POSTYes
PUTYes
PATCHYes
DELETEUsually no, although some APIs support it
HEADNo
OPTIONSUsually no

Common Request Body Formats

APIs can accept different request body formats. The most common format in REST APIs is JSON. SOAP services commonly use XML. HTML-style form submissions may use form URL encoding. File uploads often use multipart form data. Some APIs accept plain text, CSV, PDF, images, or binary streams depending on the use case.

The request body format must match the Content-Type header. If the body is JSON, the header should normally be Content-Type: application/json. If the body is XML, the header may be Content-Type: application/xml. If the body is multipart form data, the header is multipart/form-data with a boundary value generated by the client or tool.

For testers, body format coverage includes correct format, unsupported format, malformed format, missing Content-Type, and mismatched body and Content-Type. Format defects often appear before business validation because the server cannot apply business rules until it can parse the payload.

JSON Request Body

JSON is the most common request body format for REST APIs. It is lightweight, readable, easy to generate, and widely supported by modern programming languages and testing tools. A JSON body can contain strings, numbers, booleans, null values, objects, and arrays.

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

JSON request bodies are commonly used for user creation, login, order placement, product updates, search requests, and many other operations. The server parses the JSON into application objects and validates the fields against schema and business rules.

Testing JSON bodies should include valid JSON, invalid JSON, missing fields, extra fields, wrong data types, null values, empty strings, arrays, nested objects, maximum lengths, enum values, and malicious strings. Invalid JSON, such as trailing commas or missing quotes, should produce a controlled client error instead of a server crash.

XML Request Body

XML request bodies are common in SOAP services and may also appear in some REST APIs. XML is more verbose than JSON, but it supports attributes, namespaces, schemas, and formal document structure. SOAP messages are XML-based by design.

<User>
  <Name>John</Name>
  <City>Chicago</City>
</User>

When testing XML request bodies, testers must pay attention to tags, hierarchy, namespaces, schema rules, encoding, and required elements. A small namespace mistake can cause a SOAP or XML API to reject the message. XML validation often uses XPath, XSD schema validation, or SOAP-specific tooling.

Security testing for XML may also include XML external entity risks where applicable, oversized XML payloads, deeply nested XML, and malformed XML. The API should parse XML safely and reject invalid input with clear errors.

Form Data

Form URL encoded data is commonly used by traditional HTML forms and some authentication endpoints. Instead of JSON, the body contains key-value pairs such as username=john&password=secret. The Content-Type is usually application/x-www-form-urlencoded.

This format is simple and useful for flat data, but it is not ideal for complex nested objects. OAuth token endpoints commonly use form URL encoded bodies, which is why API testers still encounter this format in modern systems.

Testing form data includes required keys, missing keys, invalid values, URL encoding, special characters, repeated keys, and sensitive values. Since credentials are often sent through form data, HTTPS and secure logging are important.

Multipart Form Data

Multipart form data is used when a request needs to upload files along with optional fields. Examples include profile photos, resumes, identity documents, invoices, reports, attachments, and product images. The body is divided into parts, and each part can have its own headers and content.

A multipart request may contain a file part named resume and text fields such as candidateId or documentType. The Content-Type is multipart/form-data with a boundary. Tools such as Postman and REST Assured usually generate the boundary automatically.

Testing multipart bodies includes valid file upload, missing file, invalid file type, oversized file, empty file, corrupted file, multiple files, missing metadata, invalid metadata, virus scanning behavior where applicable, and storage or download verification after upload.

POST Request Body

POST requests commonly use a request body to create a resource or submit data for processing. A user creation request may call POST /users with a JSON body containing name and email. An order placement request may call POST /orders with customer, items, address, and payment details.

A successful POST that creates a resource often returns 201 Created, sometimes with the created resource in the response body and a Location header pointing to the new resource. Some POST operations return 200 OK or 202 Accepted depending on whether the operation is synchronous or asynchronous. The contract should define expected behavior.

POST body testing should include valid creation, missing required fields, duplicate values, invalid data, boundary values, business rule failures, authorization failures, and idempotency strategy where required. For payment or order systems, duplicate POST requests are especially important because accidental retries should not create duplicate business results unless the API is designed that way.

PUT Request Body

PUT requests usually send a complete replacement representation of an existing resource. If PUT /users/101 is called, the request body should contain the full updated user representation according to the API contract. Fields omitted from the PUT body may be cleared, defaulted, rejected, or left unchanged depending on implementation, but the expected behavior should be documented.

Testing PUT requires checking complete updates, missing fields, full replacement behavior, invalid data, unchanged repeated requests, and idempotency. PUT should generally be idempotent: sending the same PUT request multiple times should leave the resource in the same final state.

Testers should not assume PATCH behavior for PUT. If only one field is sent in a PUT body and other fields disappear, that may be correct replacement behavior. If the API intends partial update, PATCH may be the better method.

PATCH Request Body

PATCH requests send partial changes to an existing resource. For example, PATCH /users/101 may send only {"email":"newemail@example.com"} to update the email while leaving other fields unchanged. PATCH is useful when clients need to update a small part of a resource.

PATCH body testing should verify that only specified fields change. Unspecified fields should remain unchanged unless the contract says otherwise. Tests should include valid partial updates, invalid fields, unsupported fields, null values, empty values, field-level authorization, and business rule validations.

Some APIs use JSON Merge Patch or JSON Patch formats. These formats have specific rules and should be tested according to their standards. Other APIs use custom partial JSON bodies. The testing approach should follow the API specification.

Request Body vs Request Headers

Request body and request headers serve different purposes. The request body contains business data. Request headers contain metadata. For example, a user creation body may contain name, email, and city. The headers may contain Authorization, Content-Type, Accept, tenant ID, and correlation ID.

Request Body Request Headers
Contains business dataContains metadata
Sent after headersSent before the body
Usually JSON, XML, form data, or filesKey-value pairs
Example: user detailsExample: Authorization

Both must be correct. A valid JSON body may fail if Content-Type is missing. A valid token may not help if the body violates business rules. Strong API testing validates headers and body together.

Request Body vs Query Parameters

Request bodies and query parameters are also different. Query parameters are usually simple key-value pairs used to filter, sort, search, paginate, or customize a request. Request bodies are better for complex data such as nested objects, arrays, credentials, order details, and structured updates.

A request such as GET /users?city=Chicago uses a query parameter to filter users. A request such as POST /users sends a body to create a new user. A long URL containing name, address, email, password, and preferences is usually a sign that data should be moved into the request body.

Testers should verify that APIs use query parameters and request bodies appropriately. Complex or sensitive data in URLs can create logging, length, encoding, and security problems.

Complex JSON Request Body

Real request bodies often contain nested objects and arrays. A simple flat body may be enough for beginner examples, but production APIs usually handle richer structures. For example:

{
  "id": 101,
  "name": "John",
  "address": {
    "city": "Chicago",
    "zip": "60007"
  },
  "skills": [
    "Java",
    "Selenium",
    "API Testing"
  ]
}

This body contains a number, strings, a nested object, and an array. Each level may have its own validation rules. Address city may be required. Zip may need a specific format. Skills may have a maximum size or may reject duplicate values. Testing should cover nested validation, not only top-level fields.

Empty Request Body

Some requests intentionally have no body. GET /users usually retrieves users without a body. DELETE /users/101 often deletes a user without a body. A missing body is valid when the method and endpoint do not require one.

However, an empty body can be invalid for POST, PUT, or PATCH endpoints that require data. POST /users with no body should usually return a validation error or bad request response. PATCH /users/101 with an empty body may be rejected because there are no changes to apply.

Testers should verify both intentional empty body behavior and accidental missing body behavior. The expected result depends on the API contract, but the response should be controlled and meaningful.

Request Body Validation in API Testing

Request body validation starts with required fields. If email is mandatory during user creation, a body without email should return a clear validation error. The API should identify the missing field and avoid creating an incomplete resource.

Missing fields, invalid data types, boundary values, empty strings, null values, extra fields, nested object errors, array errors, enum errors, and malformed payloads should all be tested. For example, if age must be a number, "age":"twenty" should fail. If age must be between 18 and 120, values such as 17, 18, 120, and 121 should be tested.

Extra fields require clear behavior. Some APIs ignore unknown fields. Others reject them. Both can be valid, but the choice should be documented. Silent acceptance of unknown fields can hide client mistakes. Strict rejection can protect the contract but may reduce flexibility.

Nested objects and arrays require deeper validation. An address object may require city and zip. A skills array may reject duplicates or have a maximum length. An order items array may require at least one item, valid product IDs, positive quantities, and available inventory.

Security Testing with Request Bodies

Request bodies are a common attack surface because they accept input from clients. Security testing should include SQL injection strings, XSS payloads, command-like input, oversized payloads, deeply nested JSON, unexpected data types, invalid encoding, and malicious file uploads where applicable.

A username value such as ' OR 1=1-- should not bypass authentication or return unauthorized data. A name value such as <script>alert(1)</script> should be handled safely according to the application's validation and output encoding strategy. The API should not crash or expose stack traces when malicious input is submitted.

Large bodies should be limited. Without size limits, clients may send huge payloads that consume memory or processing resources. Nested JSON depth should also be controlled if the parser or business logic is vulnerable to expensive processing. File uploads should validate file size, type, content, and storage behavior.

Security testing should also verify that sensitive fields are handled safely. Passwords should be transmitted over HTTPS, not logged in plain text, and stored securely by the backend. Payment details should follow the required security and compliance model. Request body testing is therefore both functional and security-focused.

Request Body Validation Checklist

A practical request body checklist includes required fields, optional fields, missing fields, empty values, null values, invalid data types, boundary values, maximum length, minimum length, nested objects, arrays, enum values, duplicate values, special characters, malformed JSON, unsupported media types, SQL injection, XSS injection, and business validation rules.

Business validation is often more important than basic schema validation. A schema may confirm that quantity is a number, but business rules decide whether quantity can be zero, whether product inventory is available, whether the customer can place the order, and whether the payment method is allowed. Tests must cover both schema-level and business-level validation.

Negative tests should assert clear error responses. A useful error response identifies the failed field, the reason, and possibly an application error code. A vague response such as Invalid request may be technically correct but unhelpful for clients. Testers should evaluate error quality, not only status codes.

REST Assured Example

REST Assured allows request bodies to be sent as strings, objects, maps, files, or serialized Java objects. A simple JSON string example looks like this:

String body = """
{
  "name": "John",
  "city": "Chicago"
}
""";

given()
  .contentType("application/json")
  .body(body)
  .when()
  .post("/users")
  .then()
  .statusCode(201);

In larger frameworks, request bodies are often built using POJOs, builders, maps, JSON files, or test data factories. This helps create reusable and readable payloads. However, negative tests may still need direct control over malformed or invalid payloads.

Postman Example

In Postman, a tester can select the Body tab, choose raw, select JSON, and enter a payload such as:

{
  "name": "John",
  "city": "Chicago"
}

Postman can automatically set the Content-Type header when JSON is selected, but testers should still verify the final request. Variables can be used inside request bodies, such as {{email}} or {{userId}}, making the request reusable across environments and data sets.

Postman tests can validate response behavior after sending the body. Newman can run the same collection in CI/CD. For body-heavy APIs, Postman collections should include positive examples, negative examples, and boundary examples, not only one happy path.

Karate Example

Karate makes JSON request bodies readable inside feature files. A request can be written like this:

Given request
"""
{
  "name": "John",
  "city": "Chicago"
}
"""
When method POST
Then status 201

Karate also supports variables, data-driven examples, JSON matching, schema-like assertions, and reading payloads from files. This makes it useful for testing complex request body variations while keeping scenarios readable.

Real-World Examples

A user registration request may send username, password, email, phone number, and address. A product creation request may send name, price, category, description, image references, and inventory details. A banking transfer request may send account number, amount, currency, reference ID, and beneficiary information.

An order placement request may send customer ID, shipping address, billing address, payment token, coupon code, and line items. A support ticket request may send title, description, priority, attachments, and category. Each of these bodies has different validation rules, security concerns, and business workflows.

Real request bodies are not only data containers. They express business intent. Good API testing validates whether the server interprets that intent correctly.

Best Practices

Send the correct Content-Type header with every request body. Validate all required fields. Use appropriate data types. Keep request bodies well-structured and aligned with the API schema. Validate nested objects and arrays carefully. Avoid sending unnecessary fields that the API does not use.

Follow the API specification for field names, formats, allowed values, required fields, optional fields, null behavior, and error responses. Protect against malicious input by validating and sanitizing where appropriate. Enforce size limits and avoid logging sensitive request body values.

In automation, use reusable builders or test data factories for valid payloads. Keep negative payloads clear and intentional. Do not hide all request body construction behind complex helpers that make tests unreadable. A tester should be able to understand what data is being sent and why.

Common Mistakes

A common mistake is sending JSON without Content-Type: application/json. The server may not parse the body correctly. Another mistake is using query parameters for complex data, such as /createUser?name=John&city=Chicago&email=john@example.com. Complex objects should usually be sent in the request body.

Invalid JSON is another frequent issue. A trailing comma, missing quote, unclosed brace, or wrong escaping can make the payload invalid before business validation even starts. Testers should distinguish malformed JSON errors from valid JSON that fails business validation.

Wrong data types also cause defects. Sending "age":"Twenty" when the API expects a number should produce a validation error. Sending arrays where objects are expected, objects where strings are expected, or nulls where values are required should all be tested.

Another mistake is ignoring optional fields. Optional does not mean unimportant. Optional fields may affect business behavior, defaults, calculations, notifications, or downstream processing. Tests should include scenarios with optional fields present and absent.

Interview Questions

A common interview question is: what is a request body? A strong answer is that a request body is the payload sent from the client to the server as part of an HTTP request. It contains business data needed to create, update, replace, or process a resource.

Another question is which HTTP methods commonly use a request body. POST, PUT, and PATCH commonly use request bodies. Some APIs may support a body with DELETE, while GET typically does not include one in common REST API practice.

Interviewers may ask the most common request body format. JSON is the most common format for modern REST APIs, while XML is common in SOAP and some older APIs. Form data and multipart form data are also common for forms and file uploads.

A testing-focused answer should mention required fields, optional fields, missing fields, invalid data types, boundary values, nested objects, arrays, nulls, empty values, malformed JSON, business rules, and security payloads.

Interview-Ready Explanation

A request body is the payload sent from the client to the server as part of an HTTP request. It contains the business data required to create, update, replace, or process a resource. Request bodies are commonly used with POST, PUT, and PATCH requests. The most common request body format in REST APIs is JSON, although XML, form data, multipart form data, plain text, and binary data are also supported depending on the API.

The request body is different from request headers and query parameters. Headers contain metadata such as Authorization and Content-Type. Query parameters usually filter or customize results. The body contains structured input data such as user details, login credentials, order information, product data, payment details, or file upload content.

In API testing, the request body should be validated for required fields, optional fields, missing fields, data types, boundary values, null values, empty strings, nested objects, arrays, enum values, duplicate values, schema rules, business rules, and security risks such as SQL injection and XSS. Correct request body validation ensures that the API handles both valid and invalid client input safely and predictably.

Key Takeaway

The request body is where most client-submitted business data lives. It is central to create, update, replace, login, upload, and workflow operations. A correct URL and valid headers are not enough if the body is malformed, incomplete, insecure, or inconsistent with business rules.

The practical rule is to test request bodies deeply. Validate structure, content type, required fields, optional behavior, boundaries, nested data, arrays, malformed payloads, and malicious input. Strong request body testing catches defects that simple status-code checks miss and gives teams confidence that the API can handle real client data.