How to Use cURL to Interact with a REST API
This guide demonstrates how to use cURL, a powerful command-line tool, to interact with REST APIs. You will learn how to perform essential HTTP methods—including GET, POST, PUT, and DELETE—as well as how to send custom headers, handle authentication, and transmit JSON data payloads directly from your terminal.
1. Sending a GET Request
The GET method is used to retrieve data from an API. By
default, cURL performs a GET request if no specific method is
defined.
curl https://api.example.com/usersTo include query parameters in your request, append them to the URL
using a question mark (?):
curl "https://api.example.com/users?limit=10&status=active"Note: Always wrap URLs with query parameters in quotation marks
to prevent the terminal from misinterpreting the &
character.
2. Sending a POST Request
The POST method is used to send data to a server to
create a new resource. Use the -X POST option to specify
the request method and -d to send the payload.
To send JSON data, you must also define the Content-Type
header using the -H option:
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name": "Alice Smith", "email": "alice@example.com"}'3. Sending a PUT Request
The PUT method is used to update an existing resource or
replace it entirely. It uses the same structure as a POST request but
with -X PUT.
curl -X PUT https://api.example.com/users/123 \
-H "Content-Type: application/json" \
-d '{"name": "Alice Jones", "email": "alice.jones@example.com"}'4. Sending a DELETE Request
The DELETE method is used to remove a specified resource
from the server.
curl -X DELETE https://api.example.com/users/1235. Handling Authentication
Many APIs require authentication. You can send authorization credentials using custom headers.
Bearer Token Authentication
curl https://api.example.com/protected \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"Basic Authentication
For Basic Auth, you can use the -u flag to pass username
and password credentials:
curl -u username:password https://api.example.com/protected6. Useful cURL Flags for Debugging
When interacting with APIs, you often need to inspect the details of the request and response.
-i(Include headers): Displays the HTTP response headers along with the response body.curl -i https://api.example.com/users-v(Verbose): Provides a step-by-step log of the entire request/response cycle, which is highly useful for troubleshooting connection or SSL issues.curl -v https://api.example.com/users-o(Output file): Saves the API response directly to a file instead of displaying it in the terminal.curl https://api.example.com/data.json -o response.json