API Response Parsing
Description
Structured extraction and validation of data from REST, GraphQL, gRPC, and WebSocket API responses. Handles deeply nested payloads, pagination envelopes, error schemas, partial responses, and dynamic field resolution. Includes schema validation, type coercion, and tolerance for malformed or evolving APIs.
When to Use
- Consuming third-party REST or GraphQL APIs where the schema may drift
- Extracting structured data from paginated or cursor-based response envelopes
- Validating API responses against OpenAPI / JSON Schema before downstream processing
- Handling gRPC Protobuf responses that must be decoded and mapped to domain objects
Example
import httpx, jsonpath_ng
from jsonschema import validate
SCHEMA = {
"type": "object",
"required": ["data", "meta"],
"properties": {
"data": {"type": "array", "items": {"type": "object"}},
"meta": {"type": "object", "properties": {"next_cursor": {"type": "string"}}}
}
}
def fetch_all_pages(url: str, headers: dict) -> list[dict]:
results, cursor = [], None
while True:
params = {"cursor": cursor} if cursor else {}
r = httpx.get(url, headers=headers, params=params, timeout=10)
r.raise_for_status()
body = r.json()
validate(instance=body, schema=SCHEMA) # raises on malformed payload
expr = jsonpath_ng.parse("$.data[*].id")
ids = [m.value for m in expr.find(body)]
results.extend(body["data"])
cursor = body.get("meta", {}).get("next_cursor")
if not cursor:
break
return results
Advanced Techniques
- GraphQL fragment unpacking: recursively resolve
__typename to dispatch handlers per concrete type
- Protobuf → dict: use
google.protobuf.json_format.MessageToDict with preserving_proto_field_name=True
- Delta patching: for PATCH-style APIs returning only changed fields, merge with a local baseline using
deepmerge
- Rate-limit header parsing: extract
X-RateLimit-Remaining / Retry-After to back off gracefully
Related Skills
web-scraping, json-transformation, schema-inference, http-request, data-cleaning
Failure Modes
| Failure Mode |
Cause |
Mitigation |
| Untrusted input causes incorrect extraction |
Malformed, adversarial, or incomplete source data |
Validate structure, bound input size, preserve source provenance, and reject ambiguous results when required |
| Model or parser overstates certainty |
Heuristic extraction is treated as authoritative |
Return source spans or structured evidence and distinguish extraction from verification |
| Context or resource exhaustion |
Large files, histories, responses, or media are processed without limits |
Apply size, time, row, page, or token limits and process incrementally |
Evidence
The skill's implementation guidance is grounded in the following primary references:
Evidence status: implementation guidance verified against the cited documentation; no benchmark claim is made unless a reproducible benchmark is included in this file.
1---2name: api-response-parsing3description: Parse and validate REST, GraphQL, gRPC, and WebSocket responses into bounded, typed structures, including pagination, error envelopes, schema drift, and partial responses.4metadata:5 source: https://skillmd.com/skills/samotech/api-response-parsing6 upstream: skills/01-perception/api-response-parsing.md7 category: 01-perception8 version: "v2"9---10111213# API Response Parsing1415### Description16Structured extraction and validation of data from REST, GraphQL, gRPC, and WebSocket API responses. Handles deeply nested payloads, pagination envelopes, error schemas, partial responses, and dynamic field resolution. Includes schema validation, type coercion, and tolerance for malformed or evolving APIs.1718### When to Use19- Consuming third-party REST or GraphQL APIs where the schema may drift20- Extracting structured data from paginated or cursor-based response envelopes21- Validating API responses against OpenAPI / JSON Schema before downstream processing22- Handling gRPC Protobuf responses that must be decoded and mapped to domain objects2324### Example25```python26import httpx, jsonpath_ng27from jsonschema import validate2829SCHEMA = {30 "type": "object",31 "required": ["data", "meta"],32 "properties": {33 "data": {"type": "array", "items": {"type": "object"}},34 "meta": {"type": "object", "properties": {"next_cursor": {"type": "string"}}}35 }36}3738def fetch_all_pages(url: str, headers: dict) -> list[dict]:39 results, cursor = [], None40 while True:41 params = {"cursor": cursor} if cursor else {}42 r = httpx.get(url, headers=headers, params=params, timeout=10)43 r.raise_for_status()44 body = r.json()45 validate(instance=body, schema=SCHEMA) # raises on malformed payload46 expr = jsonpath_ng.parse("$.data[*].id")47 ids = [m.value for m in expr.find(body)]48 results.extend(body["data"])49 cursor = body.get("meta", {}).get("next_cursor")50 if not cursor:51 break52 return results53```5455### Advanced Techniques56- **GraphQL fragment unpacking**: recursively resolve `__typename` to dispatch handlers per concrete type57- **Protobuf → dict**: use `google.protobuf.json_format.MessageToDict` with `preserving_proto_field_name=True`58- **Delta patching**: for PATCH-style APIs returning only changed fields, merge with a local baseline using `deepmerge`59- **Rate-limit header parsing**: extract `X-RateLimit-Remaining` / `Retry-After` to back off gracefully6061### Related Skills62- `web-scraping`, `json-transformation`, `schema-inference`, `http-request`, `data-cleaning`636465## Failure Modes6667| Failure Mode | Cause | Mitigation |68|---|---|---|69| Untrusted input causes incorrect extraction | Malformed, adversarial, or incomplete source data | Validate structure, bound input size, preserve source provenance, and reject ambiguous results when required |70| Model or parser overstates certainty | Heuristic extraction is treated as authoritative | Return source spans or structured evidence and distinguish extraction from verification |71| Context or resource exhaustion | Large files, histories, responses, or media are processed without limits | Apply size, time, row, page, or token limits and process incrementally |727374## Evidence7576The skill's implementation guidance is grounded in the following primary references:77- JSON Schema 2020-12: https://json-schema.org/specification78- JSON Schema Validation: https://json-schema.org/draft/2020-12/json-schema-validation79- Python jsonschema validator API: https://python-jsonschema.readthedocs.io/8081Evidence status: implementation guidance verified against the cited documentation; no benchmark claim is made unless a reproducible benchmark is included in this file.