curl with Custom HTTP Headers
Add custom HTTP headers to curl requests including Authorization, Content-Type, and Accept. Learn header management and convert header patterns to code.
Detailed Explanation
Working with Custom Headers in curl
HTTP headers carry metadata about the request and are essential for authentication, content negotiation, and API versioning. curl provides the -H flag to set any custom header.
Setting a Single Header
curl -H "Authorization: Bearer eyJhbGci..." https://api.example.com/me
Setting Multiple Headers
Chain multiple -H flags for additional headers:
curl https://api.example.com/data \
-H "Authorization: Bearer eyJhbGci..." \
-H "Accept: application/json" \
-H "X-Request-ID: abc-123" \
-H "Cache-Control: no-cache"
Common Headers
- Content-Type: Tells the server the format of the request body (
application/json,text/xml,multipart/form-data) - Accept: Tells the server what response format you prefer
- Authorization: Carries credentials (Bearer tokens, Basic auth, API keys)
- User-Agent: Identifies the client making the request
- X-Custom-Header: Application-specific headers prefixed with
X-
Removing Default Headers
curl sets some headers automatically (like User-Agent). To remove a default header, set it with an empty value:
curl -H "User-Agent:" https://api.example.com/data
Reading Headers from a File
For complex header configurations, store them in a file and use -H @headers.txt (curl 7.55+):
curl -H @headers.txt https://api.example.com/data
Viewing Request Headers
Use -v to see the exact headers curl sends:
curl -v https://api.example.com/data
The lines prefixed with > show outgoing request headers, while < shows incoming response headers. This is invaluable for debugging header-related issues in API integrations.
Headers are the first thing to check when an API returns unexpected errors, as incorrect Content-Type or missing Authorization headers are among the most common causes of 400 and 401 responses.
Use Case
An API consumer needs to pass authentication tokens, specify response formats, and include tracking headers when integrating with a third-party service.