How to URL Encode Data for a cURL Request Parameters


If you are wondering how to URL encode the data that you pass as query string or parameters for an HTTP request using cURL, you need to take a look at the --data-urlencode option

Let's look at the man page.

% man curl
....
....
--data-urlencode <data>
              (HTTP) This posts data, similar to the other -d, --data options with the exception that this performs URL encoding.

              To be CGI-compliant, the <data> part should begin with a name followed by a separator and a content specification. The <data> part
              can be passed to curl using one of the following syntaxes:

              content
                     This will make curl URL-encode the content and pass that on. Just be careful so that the content does not contain any = or @
                     symbols, as that, will then make the syntax match one of the other cases below!

              =content
                     This will make curl URL-encode the content and pass that on. The preceding = symbol is not included in the data.

              name=content
                     This will make curl URL-encode the content part and pass that on. Note that the name part is expected to be URL-encoded
                     already.

              @filename
                     This will make curl load data from the given file (including any newlines), URL-encode that data and pass it on in the POST.

              name@filename
                     This will make curl load data from the given file (including any newlines), URL-encode that data and pass it on in the POST.
                     The name part gets an equal sign appended, resulting in name=urlencoded-file-content. Note that the name is expected to be
                     URL-encoded already.
...
...
Examples:
curl --data-urlencode name=val https://example.com
curl --data-urlencode =encodethis https://example.com
curl --data-urlencode name@file https://example.com
curl --data-urlencode @fileonly https://example.com

Example:
curl -X POST \
--data-urlencode "user=101" \
--data-urlencode "date=2023-06-23" \
--data-urlencode "location=New York" https://code2care.org/v1/api/data/
URL Encode Data for a cURL Request Parameters

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap