cURL by Example: Request Headers
Custom headers. This sample shows sending User-Agent and Accept headers.
Code
# Setting a custom header
curl -H "X-Api-Key: 12345" https://api.example.com/data
# Multiple headers
curl -H "Accept: application/json" \
-H "Content-Type: application/json" \
https://api.example.com/data
# Spoofing User-Agent
curl -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" https://example.com
# Empty header (removes a default header)
curl -H "Host:" https://example.comExplanation
HTTP headers allow the client and server to pass additional metadata and instructions with the request or response. Headers are fundamental to HTTP communication, controlling everything from authentication to content negotiation. You can add custom headers to your cURL request using the -H flag (or its long form --header). This is commonly used for API authentication tokens (like API keys or JWT tokens), specifying content types, custom application identifiers, cache control directives, and various other HTTP protocol features.
You can specify the -H flag multiple times to send multiple headers in a single request. Each invocation of -H adds another header to the outgoing request. Common headers include Accept (specifies what content type the client expects in the response, enabling content negotiation), Content-Type (declares what content type the client is sending in the request body), Authorization (carries authentication credentials), Cache-Control (directives for caching mechanisms), and application-specific custom headers often prefixed with X- (though this convention is deprecated in newer standards). Setting an empty header value (e.g., -H "Host:") removes a default header that cURL would normally send.
The User-Agent header identifies the client software making the request. cURL has a dedicated flag -A (or --user-agent) specifically for setting this header, which is more convenient than using -H "User-Agent: ...". By default, cURL identifies itself with a User-Agent string like "curl/7.x.x". Customizing this is useful for testing how servers respond to different browsers or clients, simulating mobile or desktop browsers, bypassing basic bot detection mechanisms, or ensuring compatibility with servers that check for specific client types. Many web servers and APIs alter their responses based on the User-Agent header, making this a crucial testing parameter.
Code Breakdown
-H "Key: Value" adds a generic HTTP header.-A "..." sets the User-Agent header specifically.
