Modern examples of best practices for JSON in APIs
Real-world examples of best practices for JSON in APIs
Before definitions and theory, let’s start with patterns you can reuse. Modern teams want examples of best practices for JSON in APIs that are battle-tested, not invented in a vacuum.
Here are some realistic scenarios you’ll recognize from day-to-day work:
- A public REST API that needs predictable pagination and filtering.
- A mobile backend that must keep payloads small for slow networks.
- A partner integration that requires stable field names and clear versioning.
- An internal microservice mesh where consistent error JSON speeds up debugging.
In each of these, the best examples of JSON design share the same traits: consistency, explicitness, and respect for clients that will live with your decisions for years.
Naming and structure: examples of clean JSON design
One of the simplest examples of best practices for JSON in APIs is consistent naming and predictable structure.
Use consistent casing and pluralization
Pick a casing convention and stick to it. Most modern HTTP APIs prefer snake_case or camelCase. Mixing them is a quiet way to create bugs.
Good example of consistent naming:
{
"user_id": "12345",
"full_name": "Jordan Smith",
"email": "jordan@example.com",
"created_at": "2025-10-01T12:34:56Z"
}
Here you get:
snake_caseeverywhere- ISO 8601 timestamp
- Stable field names that are easy to document
Compare that with a bad example:
{
"userId": "12345",
"FullName": "Jordan Smith",
"email_address": "jordan@example.com",
"createdAt": "10/01/25 12:34:56"
}
Now you have mixed casing, inconsistent naming, and a locale-specific date that’s hard to parse.
Favor flat, predictable objects over deep nesting
Deeply nested JSON might look elegant to the author, but it punishes clients. A better pattern is shallow, predictable objects with clear sub-objects only where they add meaning.
Better structured example:
{
"id": "inv_987",
"status": "paid",
"currency": "USD",
"total_amount": 199.00,
"customer": {
"id": "cus_123",
"email": "buyer@example.com"
},
"created_at": "2025-11-20T09:21:00Z"
}
This is easy to scan, easy to document, and easy to extend.
Versioning: examples of forward-compatible JSON APIs
API teams often ask for examples of best practices for JSON in APIs when it comes to versioning, because this is where breaking changes get expensive.
Prefer URL or media-type versioning over field hacks
A clean pattern is versioning in the URL or via content negotiation, while keeping JSON fields stable within that version.
URL versioning example:
GET /v1/users/123
Accept: application/json
Later, you can introduce a new version:
GET /v2/users/123
Accept: application/json
Within each version, you maintain backward compatibility: new fields are additive, existing fields keep their meaning, and removed fields are deprecated over time.
Add fields, don’t repurpose them
If status used to be "active" | "inactive", and you later add "suspended", clients that treat it as a string are fine. But if you change status from a string to an object, clients break.
Good evolution example:
// v1
{
"status": "active"
}
// v2 (additive)
{
"status": "active",
"status_reason": "email_verified"
}
This is one of the best examples of JSON evolution: never change the type of an existing field; instead, add new ones.
Error handling: examples include structured JSON errors
Developers remember your API by how it fails. The best examples of modern APIs use a consistent JSON error format.
Use a standard error envelope
A widely used pattern looks like this:
{
"error": {
"code": "invalid_request",
"message": "The 'email' field is required.",
"details": [
{
"field": "email",
"issue": "missing"
}
],
"request_id": "req_9f8d7c6b"
}
}
Why this works:
codeis machine-friendly and stable.messageis human-readable and localizable.detailssupports field-level validation feedback.request_idties into your logs.
This mirrors patterns recommended by many production APIs and aligns with guidance on clear error messaging you’ll see in usability research from organizations like NIST.
Align HTTP status codes with error JSON
If the JSON error says invalid_request but the HTTP status is 200, you’re forcing clients to parse every response before knowing if it failed.
Better mappings:
400for validation errors401for auth failures403for permission issues404for missing resources429for rate limiting5xxfor server-side problems
Your JSON and HTTP layer should tell the same story.
Pagination and filtering: concrete examples of scalable JSON
Once your dataset grows, pagination and filtering patterns become one of the most visible examples of best practices for JSON in APIs.
Cursor-based pagination
Offset-based pagination (?page=2&limit=50) is simple but fragile at scale. Cursor-based pagination is more stable for frequently changing datasets.
Cursor-based example:
GET /v1/transactions?limit=50
{
"data": [
{ "id": "txn_1", "amount": 25.50 },
{ "id": "txn_2", "amount": 99.00 }
],
"pagination": {
"next_cursor": "txn_2",
"has_more": true
}
}
Clients pass next_cursor back:
GET /v1/transactions?limit=50&cursor=txn_2
This pattern is used by many large APIs because it’s stable under concurrent writes.
JSON for filters
Expose filters as clear query parameters, but return them in JSON so clients can debug their own requests.
Filter echo example:
{
"filters": {
"status": "paid",
"created_after": "2025-01-01T00:00:00Z"
},
"data": [ ... ]
}
This is a small touch that pays off when you’re debugging complex queries in logs or client apps.
Data validation and JSON Schema: examples from production systems
Validation is where API design meets safety. Teams often look for examples of best practices for JSON in APIs that use JSON Schema or similar tools to keep contracts honest.
Use JSON Schema for contracts
JSON Schema lets you describe and validate payloads. Many organizations now use it as the single source of truth for their API contracts.
Simple JSON Schema example:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "UserCreateRequest",
"type": "object",
"properties": {
"email": { "type": "string", "format": "email" },
"full_name": { "type": "string", "minLength": 1 },
"age": { "type": "integer", "minimum": 13 }
},
"required": ["email", "full_name"]
}
You can use this schema to:
- Validate requests at the edge.
- Generate documentation.
- Generate client SDKs.
The JSON Schema organization maintains up-to-date guidance and tooling, and many large companies now treat schemas as part of their API governance.
Enforce formats and ranges
Don’t just accept “any string.” Use formats (email, uri, date-time) and numeric ranges to catch errors early. This aligns with broader data quality practices you’ll see discussed in technical standards from groups like NIST.
Security and privacy: practical examples in JSON design
Security isn’t just about transport (TLS); it’s also about what you choose to put in JSON. Some of the most important examples of best practices for JSON in APIs are about what not to return.
Never expose secrets or internal identifiers
Good APIs avoid leaking internal database IDs, secrets, or implementation details.
Safer identifier example:
{
"id": "user_8f3b2c",
"email": "patient@example.com",
"last_login_at": "2025-11-30T16:00:00Z"
}
The id is a stable, opaque token, not an auto-incrementing integer that reveals how many users you have.
For health-related APIs, this kind of design lines up with privacy expectations you’ll see reflected in consumer-facing guidance from sites like Mayo Clinic and MedlinePlus, where protecting personally identifiable data is non-negotiable.
Minimize sensitive data in responses
Return only what the client needs. Mask or omit sensitive fields when possible.
Masked field example:
{
"card_last4": "4242",
"card_brand": "visa",
"billing_zip": "94105"
}
Full card numbers, SSNs, or detailed health data should never live in general-purpose JSON responses.
Use structured auth errors
Security-related errors should still use your standard JSON error format, but avoid revealing too much.
Auth error example:
{
"error": {
"code": "unauthorized",
"message": "Authentication required.",
"request_id": "req_abc123"
}
}
Don’t distinguish between “user not found” and “wrong password” in error messages; that invites enumeration attacks.
Performance and payload size: examples of efficient JSON
In 2024–2025, mobile and IoT clients are still very sensitive to payload size and latency. That’s why teams keep hunting for examples of best practices for JSON in APIs that keep responses lean without becoming cryptic.
Use sparse fieldsets (field selection)
Let clients request only the fields they need.
Field selection example:
GET /v1/users/123?fields=id,full_name,avatar_url
{
"id": "123",
"full_name": "Jordan Smith",
"avatar_url": "https://cdn.example.com/avatars/123.png"
}
This pattern is especially helpful when objects have dozens of fields or embed related resources.
Avoid over-encoding and excessive nesting
Don’t base64-encode JSON inside JSON unless you have a very good reason. It bloats payloads and complicates parsing.
Bad pattern:
{
"payload": "eyJpZCI6ICIxMjMiLCAiZW1haWwiOiAiam9yZGFuQGV4YW1wbGUuY29tIn0="
}
Better pattern:
{
"id": "123",
"email": "jordan@example.com"
}
If you need compression, use HTTP-level compression (e.g., gzip, br) rather than inventing your own inside JSON.
Documentation and discoverability: examples of developer-friendly JSON
Even well-designed JSON fails if nobody can figure it out. Some of the best examples of JSON APIs in 2025 pair consistent design with strong documentation and examples.
Inline examples in OpenAPI/Swagger
Modern teams often use OpenAPI with rich JSON examples for each endpoint and schema.
Excerpt with example:
components:
schemas:
User:
type: object
properties:
id:
type: string
example: "user_8f3b2c"
email:
type: string
format: email
example: "jordan@example.com"
created_at:
type: string
format: date-time
example: "2025-11-20T09:21:00Z"
These inline examples become living documentation and power tools like client generators and mock servers.
Consistent patterns across endpoints
If your User object looks different in /users and /orders, you’re forcing developers to memorize quirks. A modern example of best practices for JSON in APIs is a shared schema reused everywhere.
This is the same mindset you see in well-structured educational materials from institutions like Harvard and MIT OpenCourseWare: consistent patterns make complex systems easier to learn.
FAQ: examples of best practices for JSON in APIs
What are some real examples of best practices for JSON in APIs I can copy today?
Some practical examples include:
- A standard error envelope with
code,message,details, andrequest_id. - Cursor-based pagination with
data,pagination.next_cursor, andpagination.has_more. - JSON Schema-based validation with clear
requiredfields and formats. - Sparse fieldsets via
?fields=query parameters. - Opaque, non-sequential IDs like
user_8f3b2cinstead of123. - Additive versioning where new fields are added but existing ones don’t change type.
These are all examples of best practices for JSON in APIs that you’ll see in many high-traffic platforms.
Can you give an example of a good JSON error response for validation failures?
A strong pattern is:
{
"error": {
"code": "invalid_request",
"message": "One or more fields are invalid.",
"details": [
{ "field": "email", "issue": "invalid_format" },
{ "field": "age", "issue": "must_be_13_or_older" }
],
"request_id": "req_123456"
}
}
This is a clear example of how to give clients enough information to fix their requests without leaking internal implementation details.
How do I balance JSON readability with performance?
Prefer readable field names and predictable structures, then optimize with:
- Field selection (
?fields=) to reduce payload size. - HTTP compression instead of custom encodings.
- Avoiding deeply nested structures that increase parsing overhead.
Readable JSON is not your bottleneck in most cases; network round trips and inefficient queries usually matter more.
Are there examples of JSON best practices specific to health or medical APIs?
Yes. Health-related APIs often:
- Use opaque identifiers instead of direct patient IDs.
- Minimize PHI (protected health information) in every response.
- Separate clinical data from operational metadata.
While clinical data models (like FHIR) can be complex, the same JSON principles apply. For more context on why data minimization matters in health, consumer-facing resources like MedlinePlus and Mayo Clinic emphasize privacy and careful handling of personal health information.
If you take nothing else from these examples of best practices for JSON in APIs, take this: pick consistent patterns, document them with real JSON examples, and refuse to break contracts lightly. Your future self—and every developer who has to integrate with your API—will thank you.
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