Practical examples of security considerations for JSON in APIs
Real-world examples of security considerations for JSON in APIs
Security conversations get abstract fast, so let’s start with real examples of security considerations for JSON in APIs that teams have actually tripped over.
One of the most common is the mass assignment problem. A REST API accepts a JSON body like:
{
"email": "user@example.com",
"role": "admin"
}
If the server-side model naively maps all JSON fields to database columns, an attacker can promote themselves to admin just by adding "role": "admin" to the JSON. This has bitten production apps in Node.js (Express + Mongoose), Ruby on Rails, and Laravel. The fix is to explicitly whitelist allowed fields instead of trusting the whole JSON object.
Another example is JSON-based injection. While JSON itself is structured, the values inside it often end up in SQL queries, NoSQL queries, or shell commands. A field like "search": "test' OR '1'='1" can still trigger SQL injection if the backend concatenates that value into a query. JSON doesn’t magically sanitize anything; it just wraps the same dangerous strings in curly braces.
You also see denial-of-service (DoS) via large or deeply nested JSON. Attackers send massive arrays or recursive objects that force your JSON parser to chew through megabytes of data or thousands of nested levels. Without limits on request size and depth, that can starve CPU and memory on your API servers.
These are just three examples of security considerations for JSON in APIs, but they illustrate the basic pattern: JSON is simple, but the way you parse, validate, and map it into your system is where security wins or loses.
Input validation: the best examples of JSON going wrong
Some of the best examples of JSON-related security failures start with weak or missing input validation.
Consider a public payments API that accepts JSON like:
{
"amount": 100,
"currency": "USD",
"callbackUrl": "https://merchant.example/callback"
}
``
If the backend doesn’t validate types, ranges, and formats, attackers can:
- Send `"amount": -9999999` to try to trigger logic bugs or balance miscalculations.
- Use `"currency": "../../etc/passwd"` in a poorly written file-based lookup.
- Inject `"callbackUrl": "http://attacker.example/steal"` and trick downstream systems into exfiltrating data.
A classic example of security considerations for JSON in APIs is **type confusion**. In JavaScript-based backends, JSON numbers, strings, and booleans can all blur together. If your authorization logic expects a boolean but gets a string like "false" or a number like `0`, you can end up with surprising truthiness behavior.
Modern guidance from organizations like NIST emphasizes strict input validation and defined schemas for API payloads. JSON Schema, OpenAPI, and similar tools let you enforce type, length, and pattern constraints before your business logic ever sees the data. Treat schema validation as a security control, not just documentation.
---
## Examples of JSON parsing and serialization pitfalls in APIs
Another rich source of examples of security considerations for JSON in APIs is the parsing and serialization layer.
### Ambiguous or permissive JSON parsing
Different languages and frameworks handle JSON quirks differently. Some older or permissive parsers allow:
- Trailing commas
- Comments inside JSON
- Duplicate keys
Duplicate keys are particularly nasty. In an object like:
```json
{
"role": "user",
"role": "admin"
}
Some parsers keep the first value, others keep the last. If a WAF or API gateway inspects the first role and your application uses the last one, an attacker might bypass security checks. This is a textbook example of security considerations for JSON in APIs where multiple components parse the same payload differently.
Insecure JSON serialization
On the response side, serialization mistakes can leak data. Imagine a user object in a backend ORM:
{
"id": 123,
"email": "user@example.com",
"passwordHash": "...",
"resetToken": "...",
"isAdmin": false
}
If your API simply does return user and lets the framework serialize the entire object, you might send passwordHash and resetToken to the client. That’s not a theoretical risk; public breach reports regularly mention APIs that exposed internal fields because developers forgot to trim the JSON output.
Stronger patterns include:
- Creating explicit DTOs (data transfer objects) that contain only safe fields.
- Using serialization annotations to exclude sensitive properties.
- Adding tests that assert sensitive fields never appear in JSON responses.
OWASP’s API Security Top 10 repeatedly calls out excessive data exposure, and JSON is usually the carrier for that mistake.
Authorization bugs: examples include mass assignment and over-posting
Authorization issues are some of the best examples of security considerations for JSON in APIs because they’re subtle and easy to miss in code review.
With over-posting or mass assignment, the attacker sends extra JSON fields that your UI never exposes. For example, a profile update endpoint might expect:
{
"displayName": "Jamie",
"bio": "API writer"
}
But the underlying model also has isAdmin and accountStatus fields. If the server blindly maps the JSON object to the model, an attacker can send:
{
"displayName": "Jamie",
"bio": "API writer",
"isAdmin": true,
"accountStatus": "active"
}
Suddenly they’ve escalated privileges or reactivated a banned account. This is an example of security considerations for JSON in APIs where business logic and serialization settings intersect.
The correct pattern is field-level authorization:
- Only allow specific, whitelisted fields to be updated from JSON.
- Enforce role checks before changing sensitive fields.
- Use separate endpoints for actions like role changes, not generic JSON updates.
Denial-of-service: JSON size and structure as a weapon
Attackers love cheap ways to exhaust your resources, and JSON is a perfect vehicle.
Oversized payloads
APIs that accept file uploads or bulk data in JSON can be hammered with multi-megabyte or even gigabyte-scale bodies. Without request size limits at the reverse proxy or API gateway, your JSON parser will happily read until the process or container runs out of memory.
Real examples of security considerations for JSON in APIs here include:
- Log ingestion endpoints that accept giant JSON arrays.
- Analytics APIs that allow arbitrary event batches.
- Search or filter endpoints that accept unbounded filter objects.
Mitigations are straightforward:
- Set maximum body size in your HTTP server and gateway.
- Limit array lengths and object depth via schema.
- Reject requests early if they exceed configured thresholds.
Deeply nested JSON
Even if the total size is small, deeply nested JSON can cause stack overflows or extreme CPU usage during parsing. A payload with thousands of nested objects like:
{"a":{"a":{"a":{"a":{ ... }}}}}
can tie up a single worker thread or process. This becomes particularly dangerous in single-threaded environments or serverless functions with tight timeouts.
Again, schema validation and parser configuration are your friends. Many JSON libraries allow you to set maximum depth or recursion limits.
JWTs and tokens: examples of JSON-related auth failures
JSON Web Tokens (JWTs) are a specialized JSON format, and they give us some of the most widely discussed examples of security considerations for JSON in APIs.
Historical incidents have included:
- Algorithm confusion: Some early JWT libraries accepted a token that claimed
"alg": "none"and then skipped signature verification. Attackers could forge tokens by editing the JSON header and payload. Modern libraries have fixed this, but it’s still a cautionary example. - Weak keys: Developers using short or guessable HMAC secrets for signing JWTs, which attackers could brute-force.
- Overstuffed claims: Tokens containing sensitive data like roles, internal IDs, or even PII in the JSON payload, then being logged or stored in places that aren’t access controlled.
If you’re using JWTs, treat them as another place where JSON can leak or be abused. Keep payloads minimal, enforce strict algorithms, and rotate keys regularly. The OWASP Cheat Sheet Series on authentication and JWTs is a good reference for current best practices.
CORS, JSON, and browser-based attacks
When your JSON APIs are consumed from browsers, CORS (Cross-Origin Resource Sharing) becomes part of the JSON security story.
An example of security considerations for JSON in APIs here is an API that responds with:
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
This combination is dangerous. It effectively allows any website to make authenticated requests to your API using the user’s cookies or stored credentials. If your JSON responses include sensitive user data, you’ve just opened the door to cross-site data theft.
Safer patterns include:
- Using explicit origin whitelists instead of
*. - Avoiding
Access-Control-Allow-Credentials: trueunless absolutely required. - Using short-lived tokens in headers instead of relying on cookies.
While CORS is not JSON-specific, the risk is usually about JSON data being read by untrusted frontends, so it belongs in any list of examples of security considerations for JSON in APIs.
Logging, monitoring, and privacy: JSON as both evidence and liability
JSON payloads are often logged for debugging or analytics. That creates another class of security and privacy concerns.
Real examples include:
- Logging entire request bodies that contain passwords, tokens, or payment card data.
- Shipping JSON logs to third-party services without redacting sensitive fields.
- Using shared logging infrastructure where multiple teams can see each other’s JSON payloads.
From a security and compliance perspective, JSON logs can be both invaluable and dangerous. They help you investigate incidents, but they also expand your attack surface.
Good practices here:
- Redact or hash sensitive fields before logging.
- Classify which JSON fields are safe to log and which are sensitive.
- Protect log storage with the same rigor as production databases.
Organizations like NIST and various privacy regulators highlight logging practices in their guidance on secure systems design. While not JSON-specific, the structured nature of JSON makes it easier to selectively redact and monitor fields—if you put in the work.
2024–2025 trends that change JSON API security
The context around JSON APIs has shifted in the last few years, and that changes the best examples of security considerations for JSON in APIs you should pay attention to.
Microservices and service meshes mean JSON is flying around inside your network, not just at the edge. Internal APIs often get less security scrutiny, but the same JSON injection, over-posting, and data exposure risks apply. Lateral movement during breaches frequently targets these “internal-only” JSON endpoints.
Serverless and edge computing push JSON parsing into constrained environments. Cold starts, tight memory limits, and per-request billing make DoS via large JSON payloads more attractive to attackers, because each expensive parse costs you money.
API-first products and public developer ecosystems expose JSON schemas to the world. That’s good for documentation, but it also gives attackers a menu of fields to fuzz. Treat your OpenAPI or JSON Schema documents as something you secure and review, not just a marketing asset.
Finally, AI and data pipelines are increasingly fed directly from JSON APIs. Poisoned or adversarial JSON inputs can end up training models or driving automated decisions. That extends the impact of a single insecure JSON endpoint far beyond its original scope.
FAQ: short answers with concrete examples
Q: What are some common examples of security considerations for JSON in APIs?
Common examples include mass assignment through extra JSON fields, SQL or NoSQL injection via JSON values, large or deeply nested payloads causing DoS, JWT misconfiguration, CORS misconfigurations exposing JSON data to untrusted origins, and accidental exposure of sensitive fields in JSON responses.
Q: Can JSON itself prevent injection attacks?
No. JSON is just a data format. Values inside JSON can still contain malicious strings. You must use parameterized queries, escaping, and strict validation to prevent injection, regardless of whether the data arrived as JSON or XML.
Q: What is an example of a safe pattern for handling JSON input?
A safe pattern is to validate the JSON against a schema, map only whitelisted fields into internal models, enforce authorization on each field or action, and reject requests that exceed size or depth limits. This turns JSON from an untrusted blob into a well-defined contract.
Q: Are XML and JSON equally risky for APIs?
They have different risk profiles. XML brings XML-specific attacks like XXE and entity expansion, while JSON tends to concentrate risk in injection, data exposure, and parsing quirks. Many organizations prefer JSON today, but it still requires careful security design.
Q: How can I test my JSON APIs for security issues?
Use a mix of automated tools and manual testing. Dynamic scanners that understand JSON, schema-based fuzzing, and targeted tests for over-posting, authorization, and rate limiting are all helpful. OWASP’s testing guides and API Security Top 10 provide checklists and patterns you can adapt.
If you remember nothing else, remember this: JSON is not the security problem; how you accept, interpret, and expose JSON is. The best examples of security considerations for JSON in APIs are all about boundaries—what fields you allow, how big they can get, who can set them, and where they end up next.
Related Topics
Real‑world examples of best practices for using XML in APIs
Practical examples of parsing XML data in programming languages
Practical examples of parsing JSON data in programming languages
Real‑world examples of XML API security considerations in 2025
Practical examples of JSON for RESTful API communication examples
Modern examples of best practices for JSON in APIs
Explore More Data Formats: JSON vs XML in APIs
Discover more examples and insights in this category.
View All Data Formats: JSON vs XML in APIs