How to send a header using a HTTP request through a cURL call?

To send a header in a cURL HTTP request, use the -H or --header option followed by the header name and value. Here’s how to do it with examples:

Basic Syntax

curl -H "Header-Name: Value" [URL]

Examples

1. Single Header

# Send a "Content-Type" header for JSON
curl -H "Content-Type: application/json" https://api.example.com/data

2. Multiple Headers

# Send an "Authorization" token and a custom "X-API-Key"
curl \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "X-API-Key: abc123" \
  https://api.example.com/resource

3. User-Agent Header

# Mimic a browser or app user agent
curl -H "User-Agent: MyApp/1.0 (Linux; x64)" https://example.com

4. Custom Headers

# Send a custom "X-Request-ID" for tracking
curl -H "X-Request-ID: 89f8s3" https://api.example.com/endpoint

5. Headers with Special Characters

Use quotes to handle spaces or special characters:

curl -H "X-Custom-Header: Some Value/With Spaces" https://example.com

Common Use Cases

ScenarioExample Command
Authenticationcurl -H "Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=" https://api.example.com
API Versioningcurl -H "Accept: application/vnd.example.v2+json" https://api.example.com
CORScurl -H "Origin: https://your-domain.com" https://api.example.com
Compressioncurl -H "Accept-Encoding: gzip" https://example.com

Advanced Usage

Send Headers from a File

If headers are stored in a file (headers.txt):

Authorization: Bearer YOUR_TOKEN
X-API-Key: abc123

Use:

curl -H @headers.txt https://api.example.com

View Headers Sent (Verbose Mode)

Add -v to debug headers in the request:

curl -v -H "X-Debug: true" https://example.com

POST Data with Headers

Combine headers and data:

curl \
  -H "Content-Type: application/json" \
  -d '{"name": "John"}' \
  https://api.example.com/users

Notes

  • Headers are case-insensitive (e.g., content-typeContent-Type), but use the casing your API expects.
  • To send a header without a value, use -H "Header-Name;".
  • Avoid exposing sensitive headers (e.g., API keys) in logs or shared scripts.

Key Options

OptionDescription
-H / --headerAdd a header to the request.
-A / --user-agentShortcut for setting the User-Agent header.
-vVerbose mode (shows sent headers in the output).

Leave a Reply

Your email address will not be published. Required fields are marked *