0
0
Postmantesting~15 mins

Body validation before sending in Postman - Deep Dive

Choose your learning style9 modes available
Overview - Body validation before sending
What is it?
Body validation before sending means checking the data you want to send in an API request to make sure it is correct and complete. This helps catch mistakes like missing fields or wrong data types before the request goes out. It is like double-checking a letter before mailing it to avoid errors. In Postman, you can write tests to validate the request body before sending it.
Why it matters
Without body validation, you might send wrong or incomplete data to a server, causing errors or unexpected results. This wastes time debugging and can break your application. Validating the body before sending helps catch problems early, saving effort and making your tests more reliable. It also ensures the API receives data in the format it expects, preventing failures.
Where it fits
Before learning body validation, you should understand basic API requests and JSON data structure. After mastering body validation, you can learn about response validation, automated testing, and continuous integration for APIs. This topic fits in the middle of API testing skills, bridging request crafting and test automation.
Mental Model
Core Idea
Validating the request body before sending ensures the data is correct and complete, preventing errors and saving debugging time.
Think of it like...
It's like checking your shopping list before going to the store to make sure you have everything you need and nothing wrong is on the list.
┌───────────────────────────────┐
│       Prepare Request Body     │
├───────────────────────────────┤
│  Validate fields and formats   │
├───────────────┬───────────────┤
│ Valid?        │ Not Valid?    │
│   │           │    │          │
│   ▼           │    ▼          │
│ Send Request  │ Show Error    │
└───────────────┴───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding API Request Bodies
🤔
Concept: Learn what a request body is and why it matters in API calls.
An API request body is the data you send to a server when you want to create or update something. For example, when you sign up on a website, your name and email are sent in the request body. This data is usually in JSON format, which looks like a list of key-value pairs inside curly braces.
Result
You know what data you need to send and how it looks in JSON format.
Understanding the request body is the first step to knowing what needs validation before sending.
2
FoundationBasics of JSON Structure
🤔
Concept: Learn the rules of JSON format used in request bodies.
JSON uses keys and values inside curly braces. Keys are strings, and values can be strings, numbers, booleans, arrays, or objects. For example: {"name": "Alice", "age": 30}. JSON must be well-formed: keys and strings need quotes, commas separate pairs, and brackets must match.
Result
You can recognize correct and incorrect JSON structures.
Knowing JSON rules helps you spot syntax errors before sending requests.
3
IntermediateWriting Basic Body Validation Tests
🤔Before reading on: do you think you can check if a required field exists in the body using Postman tests? Commit to your answer.
Concept: Learn how to write simple tests in Postman to check if required fields are present in the request body.
In Postman, you can write JavaScript tests under the 'Pre-request Script' tab to check the body. For example, parse the JSON body and check if a key like 'email' exists. If not, you can stop the request or log an error. Example code: const body = pm.request.body.raw; const data = JSON.parse(body); if (!data.email) { throw new Error('Email is required'); }
Result
You can catch missing fields before the request is sent.
Validating required fields early prevents sending incomplete data that causes server errors.
4
IntermediateValidating Data Types and Formats
🤔Before reading on: do you think checking if a field is a number or string is important before sending? Commit to your answer.
Concept: Learn to check that fields have the correct data types and formats, like numbers or emails.
Besides presence, fields must have correct types. For example, 'age' should be a number, and 'email' should match an email pattern. In Postman, you can use JavaScript typeof and regex to check: if (typeof data.age !== 'number') { throw new Error('Age must be a number'); } const emailPattern = /^[^@\s]+@[^@\s]+\.[^@\s]+$/; if (!emailPattern.test(data.email)) { throw new Error('Email format is invalid'); }
Result
You prevent sending data with wrong types or bad formats.
Checking types and formats avoids subtle bugs and server rejections.
5
IntermediateUsing JSON Schema for Validation
🤔Before reading on: do you think manually writing many checks is efficient for complex bodies? Commit to your answer.
Concept: Learn to use JSON Schema, a standard way to describe and validate JSON data automatically.
JSON Schema lets you define rules for your JSON body, like required fields, types, and patterns. Postman supports JSON Schema validation with built-in functions. Example schema: { "type": "object", "required": ["email", "age"], "properties": { "email": {"type": "string", "format": "email"}, "age": {"type": "integer", "minimum": 0} } } In Postman test script: const schema = {...}; const data = JSON.parse(pm.request.body.raw); pm.test('Body matches schema', () => { pm.expect(tv4.validate(data, schema)).to.be.true; });
Result
You can validate complex bodies with less code and more accuracy.
Using JSON Schema scales validation and reduces human error.
6
AdvancedStopping Requests on Validation Failure
🤔Before reading on: do you think Postman can prevent sending a request if validation fails? Commit to your answer.
Concept: Learn how to prevent sending a request if the body validation fails in Postman.
Postman does not natively stop requests from Pre-request Scripts, but you can simulate this by throwing errors or using conditional logic. For example, throw an error in the Pre-request Script if validation fails, which stops the request execution: try { const data = JSON.parse(pm.request.body.raw); if (!data.email) throw new Error('Email missing'); } catch (e) { postman.setNextRequest(null); // stops the run throw e; } This way, the request won't be sent if validation fails.
Result
You avoid sending bad requests and wasting server resources.
Knowing how to halt requests on validation failure improves test reliability and efficiency.
7
ExpertAutomating Body Validation in CI/CD Pipelines
🤔Before reading on: do you think body validation can be automated outside Postman GUI? Commit to your answer.
Concept: Learn how to integrate body validation tests into automated pipelines using Postman CLI tools like Newman.
Newman runs Postman collections from the command line, allowing integration with CI/CD tools like Jenkins or GitHub Actions. You can write body validation tests in Postman and run them automatically on every code change. This catches errors early in development. Example command: newman run collection.json --environment env.json If body validation tests fail, the pipeline stops, preventing bad API changes from deploying.
Result
You ensure continuous quality by automating body validation in development workflows.
Automating validation catches errors early and enforces API contract consistency across teams.
Under the Hood
Postman runs JavaScript code in the Pre-request Script tab before sending the request. This code can access and parse the request body as a string, convert it to a JavaScript object, and perform checks on its structure and content. If errors are thrown or conditions fail, Postman can log messages or stop further requests in a collection run. JSON Schema validation uses a library (like tv4) to compare the body against a defined schema, checking types, required fields, and formats automatically.
Why designed this way?
Postman was designed to be flexible and scriptable, allowing users to customize request preparation and validation with JavaScript. This choice leverages a widely known language and lets users write complex logic easily. JSON Schema was adopted as a standard to avoid reinventing validation rules and to provide a common language for describing JSON data, improving interoperability and reducing errors.
┌───────────────┐
│ Pre-request   │
│ Script runs   │
├──────┬────────┤
│ Parse│ Validate│
│ Body │ Body    │
├──────┴────────┤
│ Pass?         │
├──────┬────────┤
│ Yes  │ No     │
│ Send │ Stop   │
│ Req  │ Req    │
└──────┴────────┘
Myth Busters - 4 Common Misconceptions
Quick: Do you think Postman automatically validates request bodies before sending? Commit to yes or no.
Common Belief:Postman automatically checks if the request body is valid JSON and meets API requirements before sending.
Tap to reveal reality
Reality:Postman does not automatically validate the body; you must write scripts or use JSON Schema validation explicitly.
Why it matters:Assuming automatic validation leads to sending malformed or incomplete data, causing server errors and wasted debugging.
Quick: Is it enough to check only that required fields exist in the body? Commit to yes or no.
Common Belief:Checking only that required fields exist is enough to ensure the request body is valid.
Tap to reveal reality
Reality:Fields must also have correct data types and formats; presence alone is not enough to guarantee validity.
Why it matters:Ignoring data types can cause subtle bugs or server rejections that are harder to diagnose.
Quick: Can you stop a request from sending by throwing an error in Postman's Pre-request Script? Commit to yes or no.
Common Belief:Throwing an error in the Pre-request Script will always stop the request from being sent.
Tap to reveal reality
Reality:Throwing errors can stop collection runs but does not always prevent a single request from sending; special handling is needed.
Why it matters:Misunderstanding this can lead to tests that fail but still send bad requests, causing confusion and wasted resources.
Quick: Is manual validation better than using JSON Schema for complex bodies? Commit to yes or no.
Common Belief:Manually writing validation code is better because it is more flexible than JSON Schema.
Tap to reveal reality
Reality:JSON Schema is more reliable and maintainable for complex validations and reduces human error.
Why it matters:Relying on manual checks can cause inconsistent validations and more bugs in large projects.
Expert Zone
1
Postman's Pre-request Scripts run in a sandboxed JavaScript environment with limited APIs, so some Node.js features are unavailable.
2
JSON Schema validation in Postman uses the tv4 library, which supports draft-04 of the JSON Schema standard, so newer schema features may not work.
3
When chaining requests in a collection, stopping one request on validation failure requires careful use of postman.setNextRequest(null) to avoid unintended execution.
When NOT to use
Body validation before sending is not suitable when testing server-side validation or error handling, where you want to send invalid data intentionally. In such cases, use response validation tests instead. Also, for very simple APIs, manual checks might suffice without complex schemas.
Production Patterns
In production, teams write reusable JSON Schemas stored in shared repositories and import them into Postman collections. They automate validation with Newman in CI/CD pipelines to enforce API contracts. Some use environment variables to toggle strict validation on or off depending on test stages.
Connections
Response Validation
Builds-on
Validating request bodies before sending complements response validation by ensuring both input and output meet expectations, creating full test coverage.
Continuous Integration (CI/CD)
Builds-on
Automating body validation tests in CI/CD pipelines helps catch API contract violations early, improving software quality and deployment confidence.
Data Validation in Databases
Same pattern
Both API body validation and database data validation enforce rules on data correctness before processing, preventing errors and maintaining integrity.
Common Pitfalls
#1Sending requests without checking if the body is valid JSON.
Wrong approach:const data = JSON.parse(pm.request.body.raw); // no try-catch // proceed even if JSON is invalid
Correct approach:try { const data = JSON.parse(pm.request.body.raw); } catch (e) { throw new Error('Invalid JSON body'); }
Root cause:Assuming the body is always valid JSON leads to runtime errors and failed tests.
#2Only checking if fields exist but ignoring their data types.
Wrong approach:if (!data.age) throw new Error('Age missing'); // no type check
Correct approach:if (typeof data.age !== 'number') throw new Error('Age must be a number');
Root cause:Confusing presence with correctness causes subtle bugs and server errors.
#3Throwing errors in Pre-request Script but still sending the request.
Wrong approach:throw new Error('Validation failed'); // request still sends
Correct approach:postman.setNextRequest(null); throw new Error('Validation failed'); // stops request
Root cause:Not using postman.setNextRequest(null) means the request proceeds despite errors.
Key Takeaways
Validating the request body before sending ensures your API receives correct and complete data, preventing errors.
Postman allows writing JavaScript tests to check presence, types, and formats of body fields before sending requests.
Using JSON Schema automates and scales validation, reducing manual errors and improving maintainability.
Stopping requests on validation failure saves resources and improves test reliability, but requires special handling in Postman.
Automating body validation in CI/CD pipelines enforces API contracts and catches issues early in development.