Headers in an HTTP request provide additional information about the resource to be fetched or about the client itself. Headers are sent as key-value pairs, where the key is the name of the header and the value is the data to be sent. Headers are separated from the request body by a blank line. Headers are optional, but some are required for certain requests.

Common headers include User-Agent to identify the client making the request, Accept to specify the type of response you expect, Authorization to specify the type of authentication you're using, and Content-Type to specify the type of content you're sending. While there are specific options in cURL to set some of these headers, you can manually set the headers you need or set your own custom headers.

Using custom headers in cURL is a powerful way to interact with web services, APIs, and other online resources. You can use it in your scripts and workflows to automate tasks, or you can use it to test and debug your own web services and APIs.

Steps to manually set headers in cURL:

  1. Open the terminal.
  2. Create a cURL request against the desired URL.

    $ curl http://example.com/api -v 2>&1 | grep '^>'
    > GET /api HTTP/1.1
    > Host: example.com
    > User-Agent: curl/8.1.2
    > Accept: */*
    >

    Use the -v or –verbose parameter to display detailed information about the request and the server's response, and 2>&1 | grep '^>' parameter to filter the output. These are for demonstration purposes only and are not required for normal cURL requests.

  3. Add a custom header using the -H or –header option.

    $ curl -H "User-Agent: MyTestApp/1.0" http://example.com/api -v 2>&1 | grep '^>'
    > GET /api HTTP/1.1
    > Host: example.com
    > Accept: */*
    > User-Agent: MyTestApp/1.0
    >

    Headers are sent as key-value pairs, where the key is the name of the header and the value is the data to be sent. The key and value are separated by a colon and a space. The header name is case-insensitive.

  4. Add multiple headers by including multiple -H options.

    $ curl -H "User-Agent: MyTestApp/1.0" -H "Authorization: Bearer abc123" http://example.com/api -v 2>&1 | grep '^>'
    > Host: example.com
    > Accept: */*
    > User-Agent: MyTestApp/1.0
    > Authorization: Bearer abc123
    >

    You can stack as many headers as you need for your request by repeating the -H option followed by the desired header.

  5. Store headers in a file for reuse.

    $ echo -H '"X-Custom-Header1: Value1"' > headers.txt

    Use the -H option to add a header to the file. The -H option must be enclosed in double quotes, and the header must be enclosed in single quotes. Add multiple headers by repeating the -H option.

  6. Use the -K or –config option to load headers from a file.

    $ curl -K headers.txt http://example.com/api -v 2>&1 | grep '^>'
    > GET /api HTTP/1.1
    > Host: example.com
    > User-Agent: curl/8.1.2
    > Accept: */*
    > X-Custom-Header1: Value1
    >