How to Send Custom HTTP Methods with cURL
Yes, cURL can be used to send custom HTTP methods. While cURL
defaults to standard methods like GET, POST, and PUT, you can easily
initiate requests using any custom or WebDAV HTTP verb—such as PURGE,
MERGE, or COPY—by utilizing the -X or
--request command-line flag. This article provides a
straightforward guide on how to use this flag, provides practical
examples, and explains key behaviors to keep in mind when overriding
default request methods.
The -X and
--request Option
To send a custom HTTP method, append the -X flag (or the
equivalent long-form option --request) followed by your
desired custom verb, and then specify the target URL.
The basic syntax is as follows:
curl -X METHOD URLExample: Sending a PURGE Request
Many caching servers, such as Varnish, support a custom
PURGE method to clear cached content. To send a
PURGE request to a specific URL, use:
curl -X PURGE https://example.com/cached-pageExample: Sending Data with a Custom Method
If your custom method requires a payload (such as a JSON body), you
can combine the -X option with the -d (data)
and -H (header) options:
curl -X MERGE -H "Content-Type: application/json" -d '{"status": "active"}' https://api.example.com/resourceImportant Considerations
When using custom HTTP methods with cURL, keep the following rules in mind:
- Case Sensitivity: HTTP methods are case-sensitive.
By convention, HTTP methods are written in uppercase (e.g.,
PURGE, notpurge). Ensure your custom method matches the exact casing expected by your target API. - The “Stickiness” of
-Xwith Redirects: If you use the-L(or--location) flag to make cURL follow redirects, the custom method specified by-Xwill be used for all subsequent requests in the redirect chain. This can cause errors if the redirect target does not support or expect the custom method. - Do Not Use
-Xfor Standard Defaults: Avoid using-X GETor-X POSTunnecessarily. For standard requests, cURL automatically selects the correct method based on your inputs (e.g., using-dautomatically changes the method toPOST). Manually overriding these with-Xcan interfere with cURL’s internal request handling during redirects.