Real-world examples of parsing error messages in API responses
Real examples of parsing error messages in API responses
Before talking about theory, it helps to see actual payloads. Developers don’t debug abstract concepts; they debug JSON. Let’s start with a few real examples of parsing error messages in API responses and then tease out patterns you can reuse.
Example 1: Simple REST validation error
A very common pattern in public APIs is a 4xx response with a flat JSON body. Imagine a payment API returning:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": "validation_error",
"message": "Invalid request payload",
"details": {
"email": ["Email is required", "Email format is invalid"],
"amount": ["Amount must be greater than 0"]
},
"request_id": "req_9f3a1b2c"
}
A reasonable parsing strategy:
- Treat
erroras a machine-readable code you can switch on. - Use
messageas a generic fallback for logs and user-facing text. - Iterate over
detailsto construct field-level errors for your UI. - Always log
request_idso support can trace the failure upstream.
In code (JavaScript-style pseudocode):
function parseApiError(response) {
const { status } = response;
const body = response.data || {};
return {
status,
code: body.error || "unknown_error",
message: body.message || "Unexpected error from API",
fieldErrors: body.details || {},
requestId: body.request_id || null
};
}
This is one of the simplest examples of parsing error messages in API responses, but it sets up a pattern: normalize whatever the provider sends into your own internal error format.
Example 2: RFC 7807 “problem details” error payload
More APIs are adopting the RFC 7807 “problem details” format, which standardizes error responses. A typical response looks like this:
HTTP/1.1 403 Forbidden
Content-Type: application/problem+json
{
"type": "https://api.example.com/errors/insufficient-permission",
"title": "Insufficient permission",
"status": 403,
"detail": "You do not have access to this resource.",
"instance": "/users/123/profile",
"error_code": "PERMISSION_DENIED",
"correlation_id": "c-48392"
}
A good parser will:
- Prefer
error_code(if available) as the primary machine-readable value. - Use
titleordetailfor messages. - Capture
typeandinstancefor diagnostics and documentation.
Example parsing function in Python-style pseudocode:
def parse_problem_details(resp):
body = resp.json() if resp.content else {}
return {
"status": body.get("status", resp.status_code),
"code": body.get("error_code") or body.get("type", "unknown_error"),
"title": body.get("title", "API error"),
"message": body.get("detail") or body.get("title"),
"instance": body.get("instance"),
"raw": body,
}
When you’re looking for best examples of parsing error messages in API responses, RFC 7807 support is high on the list because it gives you predictable fields across different APIs.
Example 3: GraphQL error array with path and extensions
GraphQL errors are structured differently. Instead of a single error object, you get an errors array, often mixed with partial data.
HTTP/1.1 200 OK
Content-Type: application/json
{
"data": {
"user": null
},
"errors": [
{
"message": "User not found",
"path": ["user"],
"extensions": {
"code": "NOT_FOUND",
"httpStatus": 404,
"requestId": "r-8291"
}
}
]
}
Parsing here means:
- Treating
errors[0].extensions.codeas the main error code. - Using
pathto map the error back to the field or query in your client. - Respecting
httpStatuswhen deciding retry vs. user-facing failure.
An example of parsing error messages in API responses for GraphQL might:
- Collapse multiple errors into a single normalized structure for logging.
- Or, in UI code, map each error to a specific field based on
path.
Example 4: Rate limiting with retry hints
Rate limiting is everywhere now, especially across AI, social, and payments APIs. A typical modern response:
HTTP/1.1 429 Too Many Requests
Content-Type: application/json
Retry-After: 30
{
"error": {
"code": "rate_limit_exceeded",
"message": "Too many requests. Please retry later.",
"retry_after_seconds": 30,
"limit": 100,
"window": "1m"
}
}
Parsing logic should:
- Read
Retry-Afterheader when present. - Fall back to
retry_after_secondsfrom the body. - Distinguish this error from other 4xx codes so you can back off instead of failing fast.
This is one of the more practical examples of parsing error messages in API responses because it directly impacts reliability and cost. Good parsing here means smarter retry policies and fewer outages.
Example 5: OAuth 2.0 error response
Authentication failures follow their own conventions. The OAuth 2.0 spec documents a standard structure for error responses, used widely across identity providers and large platforms. The IETF OAuth 2.0 spec defines fields like error, error_description, and error_uri.
A real-world response might look like:
HTTP/1.1 400 Bad Request
Content-Type: application/json
{
"error": "invalid_grant",
"error_description": "The provided authorization grant is invalid or has expired.",
"error_uri": "https://auth.example.com/docs/errors#invalid_grant"
}
Parsing strategy:
- Treat
erroras a stable code you can branch on (invalid_grant,invalid_client,access_denied, etc.). - Use
error_descriptionfor logs and, where appropriate, user messages. - Link
error_uriinto internal runbooks or documentation.
If you’re collecting real examples of parsing error messages in API responses for security-sensitive flows, OAuth payloads are a prime category to study.
Example 6: Batch API with mixed success and failure
Batch endpoints often return partial success. That means your parsing logic can’t treat the whole request as a single yes/no.
HTTP/1.1 207 Multi-Status
Content-Type: application/json
{
"results": [
{
"id": "123",
"status": "ok"
},
{
"id": "124",
"status": "error",
"error": {
"code": "INVALID_EMAIL",
"message": "Email format is invalid"
}
}
]
}
Parsing here means iterating over results and building a per-item outcome:
- Convert each item into either a success object or an error object.
- Aggregate error codes to detect systemic problems (for example, all failures are
INVALID_EMAIL).
This is a good example of parsing error messages in API responses where you need to think beyond the HTTP status code. The HTTP layer says “multi-status,” but the business logic lives one level down.
Example 7: Streaming / SSE error fragment
With server-sent events (SSE) and streaming APIs, errors can arrive mid-stream. You might see something like:
event: error
data: {"code":"STREAM_INTERRUPTED","message":"Upstream timeout"}
Parsing logic:
- Detect the
event: errorline. - Parse the
data:payload as JSON. - Map
codeto a retry policy or UI state (for example, show a reconnect button).
Streaming is one of the newer frontiers where developers need examples of parsing error messages in API responses that are not strictly request/response. The same principles still apply: normalize, classify, and log with enough context to debug.
Example 8: Legacy XML error you still have to support
Not everything is JSON. Many enterprise APIs still send XML:
HTTP/1.1 500 Internal Server Error
Content-Type: application/xml
<error>
<code>SERVER_ERROR</code>
<message>Unexpected database failure</message>
<timestamp>2025-02-01T12:30:45Z</timestamp>
</error>
Parsing involves:
- Converting XML to an internal structure (using an XML parser, not regex).
- Mapping
<code>and<message>into the same error model you use for JSON.
When you’re cataloging examples of parsing error messages in API responses, it’s worth including at least one XML or SOAP example because these still show up in finance, healthcare, and government integrations.
Patterns you should copy from these examples
Across all these examples of parsing error messages in API responses, a few patterns keep showing up:
- Separate transport from semantics. HTTP status codes tell you the general class of error, but the body tells you what actually went wrong.
- Normalize to your own error model. Whether the provider sends
error,error_code,code, ortype, your application should expose a single, stable shape. - Prefer machine-readable codes over strings.
INVALID_EMAILis more reliable than “Email is invalid” when you’re writing branching logic. - Keep raw payloads for debugging. Store the raw JSON/XML in logs or error tracking tools; you will need it during incident response.
For teams in regulated industries — healthcare, finance, public sector — this kind of discipline is not just nice to have. Bad error handling can cascade into data quality issues, failed integrations, and, in the worst case, safety problems. That’s why organizations like the U.S. Digital Service and various federal agencies push for consistent, documented APIs and clear error contracts.
Designing a parsing strategy that survives API changes
Modern APIs evolve quickly. Between 2024 and 2025, we’ve seen:
- Providers adding machine-readable
error_codefields to previously free-form messages. - Wider adoption of problem-details-style responses.
- More structured
extensionsmetadata in GraphQL schemas.
If you want your parsing logic to survive that churn:
- Code defensively. Assume fields may be missing, renamed, or nested differently.
- Avoid depending on full message text. Use codes for branching; treat human-readable messages as unstable.
- Feature-flag parsing behavior. When a provider announces a new error format, you can roll out parsing changes gradually.
These design choices are informed by years of real-world examples of parsing error messages in API responses that broke when an upstream team “improved” their messages without versioning.
Turning parsed errors into better UX and observability
Parsing is not just about avoiding crashes. Once you have a clean internal error model, you can:
- Show targeted UI feedback. For example, map
INVALID_EMAILto a specific inline error on an email field. - Drive metrics and alerts. Count errors by
codeandstatusto catch regressions. A spike inRATE_LIMIT_EXCEEDEDmight mean you need a better backoff strategy. - Feed incident response. Correlate
request_idorcorrelation_idfrom error payloads with upstream logs. This pattern is used heavily in large-scale systems and is echoed in guidance from organizations like NIST around traceability and logging.
Once you’ve seen enough real examples of parsing error messages in API responses, you start to treat errors as a data source, not just a nuisance.
FAQ: examples of parsing error messages in API responses
Q: Can you give a simple example of parsing error messages in API responses for a frontend form?
A: Imagine a signup form that calls /users. The API returns a 400 with details.email and details.password arrays describing validation issues. Your frontend parses those keys and maps them directly to form fields, showing inline messages like “Email is required” under the email input. That’s a straightforward example of parsing error messages in API responses that directly improves user experience.
Q: How do I handle APIs that sometimes return HTML error pages instead of JSON?
A: Treat the response Content-Type as your source of truth. If it’s not JSON or XML, fall back to a generic error with the HTTP status and a short message. Log the raw body for debugging, but do not try to scrape structured data out of HTML. Many teams implement a “safe parser” that attempts JSON first, then XML, and finally defaults to a generic error object.
Q: What are some best examples of parsing error messages in API responses for logging?
A: Good logging examples include: capturing status, a stable code, the top-level message, any request_id or correlation_id, and a truncated copy of the raw error body. That gives you enough signal to debug without drowning your logs. Many engineering teams align this structure with their observability tools and internal incident playbooks.
Q: Should I expose raw API error messages directly to end users?
A: Usually not. Raw messages can leak internal details or confuse non-technical users. A better pattern is: parse the error, map it to a user-friendly message, and keep the original text for logs and support tooling. This is especially important in domains like healthcare or finance, where guidance from organizations such as NIH and Mayo Clinic emphasizes clarity, privacy, and safety in user communication.
Q: How do I test my error parsing logic?
A: Build a small library of fixtures — JSON and XML files that represent real examples of parsing error messages in API responses you’ve seen in production. Write unit tests that feed these fixtures into your parser and assert on the normalized output. Whenever your upstream API changes its format, add a new fixture and update the tests before you touch production code.
Related Topics
Real-world examples of retrying API calls after 429 errors
Real-world examples of authentication error handling in API responses
Practical examples of exponential backoff for API retries examples in 2025
Real-world examples of parsing error messages in API responses
Explore More Error Handling in API Responses
Discover more examples and insights in this category.
View All Error Handling in API Responses