Curl POST application/x-www-form-urlencoded Guide

This article provides a quick guide on how to use the curl command-line tool to send form data using the application/x-www-form-urlencoded content type. You will learn the correct syntax, the default behaviors of curl, and how to handle special characters using URL encoding.

The Standard Curl Syntax

By default, when you use the -d (or --data) flag in curl, the tool automatically sends the request as a POST and sets the Content-Type header to application/x-www-form-urlencoded.

The most basic syntax to send form data is:

curl -d "key1=value1&key2=value2" https://api.example.com/endpoint

Explicitly Setting the Content-Type Header

While curl sets the header automatically, you can explicitly define it using the -H (or --header) flag. This is useful for clarity or when working with APIs that strictly require explicit headers:

curl -X POST \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "key1=value1&key2=value2" \
  https://api.example.com/endpoint

Handling Special Characters (URL Encoding)

If your form data contains spaces, ampersands (&), equals signs (=), or other special characters, sending them raw can break the request.

To safely encode your data, use the --data-urlencode flag instead of -d. This flag automatically URL-encodes the values for you:

curl --data-urlencode "name=John Doe" \
     --data-urlencode "email=john.doe@example.com" \
     --data-urlencode "comment=This & that" \
     https://api.example.com/endpoint

Sending Data from a File

If you have a large amount of form-encoded data, you can store it in a local file (e.g., data.txt) in key1=value1&key2=value2 format and send it using the @ symbol:

curl -d "@data.txt" https://api.example.com/endpoint