cURL
cURL is a command-line tool for transferring data using various protocols, including HTTP/HTTPS. It is lightweight, versatile, and available across many platforms.
cURL is an essential tool for testing and debugging APIs due to its simplicity and flexibility. It is frequently used in CI/CD pipelines for API health checks.
Let's make a POST request to a hypothetical API endpoint, https://api.example.com/resource, to send JSON data.
Prerequisites​
Before making API calls with cURL, ensure you:
- Have cURL installed on your system. Most Unix-based systems (like macOS and Linux) come with cURL pre-installed. On Windows, you may need to install it manually.
- Are familiar with basic command-line operations.
Request​
A POST request sends data to a server. In this example, we'll send JSON data to the API endpoint using cURL.
Examplecurl -X POST https://api.example.com/resource \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "johndoe@example.com",
"age": 30
}'
How it works​
-X POST: Specifies the HTTP method as POST.https://api.example.com/resource: The target API endpoint.-H "Content-Type: application/json": Sets theContent-Typeheader toapplication/json, indicating that the request body contains JSON data.-d: Specifies the data to be sent in the request body. Here, we send a JSON object with thename,email, andagefields.
Response​
If the API successfully processes the request, it might return a JSON response like:
{
"status": "success",
"message": "Data received successfully",
"id": "12345"
}
This response will be printed directly in your terminal.
Saving the response​
To save the response to a file, use the -o option:
curl -X POST https://api.example.com/resource \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "johndoe@example.com",
"age": 30
}' \
-o response.json
This saves the API's response to a file named response.json in your current directory.
Adding authentication​
If the API requires authentication, you can include it in the command. For example:
Basic Authentication:
curl -X POST https://api.example.com/resource \
-H "Content-Type: application/json" \
-u username:password \
-d '{
"name": "John Doe",
"email": "johndoe@example.com",
"age": 30
}'Bearer Token:
curl -X POST https://api.example.com/resource \
-H "Content-Type: application/json" \
-H "Authorization: Bearer YOUR_TOKEN_HERE" \
-d '{
"name": "John Doe",
"email": "johndoe@example.com",
"age": 30
}'
Tips for using cURL​
Verbose Mode: Use
-vto see detailed information about the request and response.curl -v -X POST https://api.example.com/resource \
-H "Content-Type: application/json" \
-d '{"name": "John Doe"}'JSON Formatting: Use tools like
jqto pretty-print JSON responses for easier reading:curl -X POST https://api.example.com/resource \
-H "Content-Type: application/json" \
-d '{"name": "John Doe"}' | jq
With these basics, you're ready to start using cURL to interact with APIs!