How to write API tests with curl

· Category: API & REST

Short answer

curl is a command-line tool for transferring data with URLs, making it ideal for quick API testing and debugging.

Steps

  1. Formulate the HTTP method with -X GET or omit it for the default GET.
  2. Add headers with -H for Content-Type, Authorization, and custom values.
  3. Send JSON bodies using -d with single quotes around the payload.
  4. Follow redirects with -L and inspect headers with -I.
  5. Save responses to files with -o or pipe them to jq for formatting.

Tips

  • Use --fail-with-body to catch HTTP errors while still printing response bodies.
  • Enable verbose mode with -v to inspect request and response headers.
  • Store reusable headers in a file and load them with -H @filename.
  • Quote URLs to prevent shell interpretation of special characters.

Common issues

  • Forgetting to set Content-Type to application/json when sending JSON bodies.
  • Shell escaping issues with nested quotes in curl commands.
  • SSL certificate errors when testing against self-signed certificates.
  • Large response bodies overwhelming the terminal output.

Example

curl -X GET https://api.example.com/users   -H "Accept: application/json"   -H "Authorization: Bearer $TOKEN"

This curl command demonstrates a standard GET request with headers for content negotiation and bearer token authentication.