Raw and Formatted API Responses
December 3, 2024When working with APIs from the command line, the way we view the response data can significantly impact our development workflow. Let's explore the difference between using plain curl
versus combining it with jq
when fetching data from the Stoic API.
Plain curl Approach
➜ curl -X GET https://stoic-api.vercel.app/api/quote -H "Content-Type: application/json" -d '{"id": 0}'{"data":{"quote":"What decides whether a sum of money is good? The money is not going to tell you; it must be the faculty that makes use of such impressions – reason.","author":"Epictetus","source":"Discourses I, 1.5","id":0}}%
When using plain curl
, the API response is returned as a raw JSON string, typically appearing as a single line of unformatted text. This output is:
- Hard to read
- Difficult to parse visually
- Challenging to identify specific data points
- Not color-coded
curl with jq
➜ curl -X GET https://stoic-api.vercel.app/api/quote -H "Content-Type: application/json" -d '{"id": 0}' | jq{"data": {"quote": "What decides whether a sum of money is good? The money is not going to tell you; it must be the faculty that makes use of such impressions – reason.","author": "Epictetus","source": "Discourses I, 1.5","id": 0}}
Using jq
as a JSON processor provides several advantages:
- Automatic pretty-printing with proper indentation
- Syntax highlighting (in supported terminals)
- Easy-to-read hierarchical structure
- Ability to parse and filter data
When to Use Which
Use plain curl
:
- When you need raw output for scripting
- When processing speed is critical
- When working with non-JSON responses
Use curl
with jq
:
- During development and debugging
- When analyzing API responses
- When you need to extract specific data
- When sharing API response examples with others
Conclusion
While both approaches fetch the same data, combining curl
with jq
provides a superior experience for development and debugging purposes. The formatted output makes it significantly easier to work with JSON responses and understand the structure of the returned data.