curl: A Versatile Tool for API Interaction
curl is a command-line tool and library for transferring data with URLs. It supports a wide range of protocols, including HTTP, HTTPS, FTP, FTPS, SCP, SFTP, and more. For API interactions, curl is an invaluable tool for testing endpoints, sending custom requests, and inspecting responses without needing a full browser or dedicated API client.
1. Sending an Authenticated GET Request
A common task when interacting with APIs is sending requests that require authentication, often using an Authorization header with a Bearer token.
curl -H "Authorization: Bearer <YOUR_API_TOKEN>" <API_ENDPOINT_URL>
# Example:
curl -H "Authorization: Bearer <EXAMPLE_API_TOKEN>" https://api.example.com/userCommand Breakdown:
curl: Invokes thecurlutility.-H "Authorization: Bearer <YOUR_API_TOKEN>": Adds an HTTP header to the request.Authorization: The header name, indicating the authentication scheme.Bearer <YOUR_API_TOKEN>: The authentication credential. A Bearer token is a cryptographic string that grants access to specific resources.
<API_ENDPOINT_URL>: The URL of the API endpoint you wish to access.
Security Note: Be cautious when using API tokens directly in the command line, as they might be stored in your shell history. For sensitive or production use, consider environment variables or secure credential management.
2. Other Common API Interaction Scenarios
Basic GET Request
curl https://api.example.com/dataPOST Request with JSON Data
To send data in the request body, typically for creating or updating resources.
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name": "New Item", "value": 123}' \
https://api.example.com/items-X POST: Specifies the HTTP method as POST.-H "Content-Type: application/json": Informs the server that the request body is in JSON format.-d '<data>': Specifies the data to send in the request body.
PUT Request with Form Data
curl -X PUT \
-d "param1=value1¶m2=value2" \
https://api.example.com/resources/1Verbose Output (-v)
To see the full request and response headers, which is very useful for debugging API calls.
curl -v https://api.example.com/statusTesting Requests Against an Echo Server
When you need to confirm exactly what curl is sending, run mendhak/http-https-echo and inspect the request details in the Docker logs.
docker run -it --rm -p 80:8080 mendhak/http-https-echo
curl http://localhost/some/path?param=value -H "X-Custom-Header: test"Ignoring SSL Certificate Validation (-k)
Use with caution, primarily for testing purposes against servers with self-signed or invalid SSL certificates.
curl -k https://api.example.com/insecure-endpointSaving Response to a File (-o)
curl -o response.json https://api.example.com/big-dataFollowing Redirects (-L)
By default, curl does not follow HTTP 3xx redirects. Use -L to enable this behavior.
curl -L http://example.com/old-page