curl Cheat Sheet for APIs
Master curl commands for testing and interacting with APIs - a comprehensive reference guide
Last updated: 8/18/2025
curl Cheat Sheet for APIs
curl is a powerful command-line tool for transferring data to and from servers. It's an essential tool for API testing, debugging and automation, allowing you to interact with web services directly from your terminal.
What Is curl?
curl (Client URL) is a command-line utility that enables you to send HTTP requests and view responses without using a web browser. It's like having a command-line version of your browser's network tab, giving you complete control over HTTP requests.
Why Use curl for APIs?
Advantages
- Command Line Access: Test APIs directly from your terminal
- Scripting Integration: Automate API testing and workflows
- Detailed Control: Customise headers, methods and request data
- Cross-Platform: Available on Windows, macOS and Linux
- No GUI Required: Perfect for server environments and CI/CD pipelines
Common Use Cases
- API Testing: Verify endpoints and test functionality
- Debugging: Troubleshoot API issues and responses
- Automation: Script API interactions for testing
- Documentation: Generate examples for API documentation
- Development: Test APIs during development and deployment
Installing curl
macOS
# curl is pre-installed on macOS
curl --version
# Or install via Homebrew for latest version
brew install curl
Linux (Ubuntu/Debian)
sudo apt update
sudo apt install curl
Linux (CentOS/RHEL)
sudo yum install curl
# Or for newer versions
sudo dnf install curl
Windows
# Using Chocolatey
choco install curl
# Using Scoop
scoop install curl
# Or download from https://curl.se/windows/
Basic curl Syntax
Command Structure
curl [options] [URL]
Basic Example
curl https://api.example.com/users
With Options
curl -X GET -H "Content-Type: application/json" https://api.example.com/users
HTTP Methods
GET Request (Default)
# Simple GET request
curl https://jsonplaceholder.typicode.com/posts/1
# GET with verbose output
curl -v https://jsonplaceholder.typicode.com/posts/1
# GET and save to file
curl -o response.json https://jsonplaceholder.typicode.com/posts/1
POST Request
# Basic POST request
curl -X POST https://jsonplaceholder.typicode.com/posts
# POST with JSON data
curl -X POST \
-H "Content-Type: application/json" \
-d '{"title": "New Post", "body": "Post content", "userId": 1}' \
https://jsonplaceholder.typicode.com/posts
# POST with data from file
curl -X POST \
-H "Content-Type: application/json" \
-d @data.json \
https://jsonplaceholder.typicode.com/posts
PUT Request
# PUT request (complete replacement)
curl -X PUT \
-H "Content-Type: application/json" \
-d '{"id": 1, "title": "Updated Post", "body": "Updated content", "userId": 1}' \
https://jsonplaceholder.typicode.com/posts/1
PATCH Request
# PATCH request (partial update)
curl -X PATCH \
-H "Content-Type: application/json" \
-d '{"title": "Updated Title"}' \
https://jsonplaceholder.typicode.com/posts/1
DELETE Request
# DELETE request
curl -X DELETE https://jsonplaceholder.typicode.com/posts/1
Headers and Authentication
Setting Headers
# Single header
curl -H "Authorization: Bearer token123" https://api.example.com/users
# Multiple headers
curl \
-H "Authorization: Bearer token123" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
https://api.example.com/users
# Custom header
curl -H "X-API-Key: your-api-key" https://api.example.com/users
Authentication Examples
# Basic authentication
curl -u username:password https://api.example.com/users
# Bearer token
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
https://api.example.com/users
# API key in header
curl -H "X-API-Key: sk_live_1234567890abcdef" \
https://api.example.com/users
# Cookie authentication
curl -b "session=abc123def456" https://api.example.com/users
Common Headers
# Content type
curl -H "Content-Type: application/json" https://api.example.com/users
# Accept header
curl -H "Accept: application/json" https://api.example.com/users
# User agent
curl -H "User-Agent: MyApp/1.0" https://api.example.com/users
# Referer
curl -H "Referer: https://example.com" https://api.example.com/users
Request Data
JSON Data
# Inline JSON
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name": "John Doe", "email": "john@example.com"}' \
https://api.example.com/users
# Pretty-printed JSON
curl -X POST \
-H "Content-Type: application/json" \
-d '{
"name": "John Doe",
"email": "john@example.com",
"age": 30
}' \
https://api.example.com/users
Form Data
# URL-encoded form data
curl -X POST \
-d "name=John Doe" \
-d "email=john@example.com" \
https://api.example.com/users
# Multipart form data
curl -X POST \
-F "name=John Doe" \
-F "email=john@example.com" \
-F "file=@profile.jpg" \
https://api.example.com/users
Query Parameters
# URL with query parameters
curl "https://api.example.com/users?page=1&limit=10&sort=name"
# Escaping special characters
curl "https://api.example.com/search?q=hello%20world"
Response Handling
Viewing Response Headers
# Show response headers only
curl -I https://api.example.com/users
# Show both request and response headers
curl -v https://api.example.com/users
# Show response headers with response body
curl -i https://api.example.com/users
Saving Responses
# Save response to file
curl -o response.json https://api.example.com/users
# Save with custom filename
curl -o "user_$(date +%Y%m%d_%H%M%S).json" https://api.example.com/users
# Append to existing file
curl -a existing.log https://api.example.com/users
Response Formatting
# Pretty-print JSON response
curl https://api.example.com/users | python -m json.tool
# Using jq for JSON processing
curl https://api.example.com/users | jq '.'
# Filter specific fields
curl https://api.example.com/users | jq '.[0].name'
Advanced Options
Verbose Output
# Show detailed information
curl -v https://api.example.com/users
# Very verbose (shows everything)
curl --trace-ascii debug.log https://api.example.com/users
Timeout and Retry
# Set timeout (seconds)
curl --max-time 30 https://api.example.com/users
# Retry on failure
curl --retry 3 https://api.example.com/users
# Retry with delay
curl --retry 3 --retry-delay 5 https://api.example.com/users
SSL and Security
# Ignore SSL certificate verification (development only)
curl -k https://api.example.com/users
# Follow redirects
curl -L https://api.example.com/users
# Maximum redirects
curl -L --max-redirs 5 https://api.example.com/users
Practical API Testing Examples
Testing JSONPlaceholder API
# Get all posts
curl https://jsonplaceholder.typicode.com/posts
# Get specific post
curl https://jsonplaceholder.typicode.com/posts/1
# Create new post
curl -X POST \
-H "Content-Type: application/json" \
-d '{"title": "Test Post", "body": "This is a test", "userId": 1}' \
https://jsonplaceholder.typicode.com/posts
# Update post
curl -X PUT \
-H "Content-Type: application/json" \
-d '{"id": 1, "title": "Updated Title", "body": "Updated body", "userId": 1}' \
https://jsonplaceholder.typicode.com/posts/1
# Delete post
curl -X DELETE https://jsonplaceholder.typicode.com/posts/1
Testing GitHub API
# Get public user profile
curl https://api.github.com/users/octocat
# Get user repositories
curl https://api.github.com/users/octocat/repos
# Search repositories
curl "https://api.github.com/search/repositories?q=curl+api&sort=stars"
Testing Weather API
# Get weather for location
curl "https://wttr.in/Sydney?format=j1"
# Get weather with custom format
curl "https://wttr.in/London?format=3"
Error Handling and Debugging
Common Error Scenarios
# Test 404 error
curl -v https://httpstat.us/404
# Test 500 error
curl -v https://httpstat.us/500
# Test timeout
curl --max-time 1 https://httpstat.us/delay/5
Debugging Techniques
# Show request details
curl -v -X POST \
-H "Content-Type: application/json" \
-d '{"test": "data"}' \
https://httpbin.org/post
# Test with httpbin.org (echoes back your request)
curl -X POST \
-H "Custom-Header: test-value" \
-d '{"message": "hello"}' \
https://httpbin.org/post
Scripting and Automation
Basic Script Example
#!/bin/bash
# Test API endpoints
echo "Testing API endpoints..."
# Test GET request
echo "Testing GET /users..."
curl -s -o /dev/null -w "Status: %{http_code}, Time: %{time_total}s\n" \
https://jsonplaceholder.typicode.com/users
# Test POST request
echo "Testing POST /users..."
curl -s -o /dev/null -w "Status: %{http_code}, Time: %{time_total}s\n" \
-X POST \
-H "Content-Type: application/json" \
-d '{"name": "Test User", "email": "test@example.com"}' \
https://jsonplaceholder.typicode.com/users
Environment Variables
#!/bin/bash
# Set API configuration
API_BASE_URL="https://api.example.com"
API_KEY="your-api-key"
# Use in curl commands
curl -H "Authorization: Bearer $API_KEY" \
"$API_BASE_URL/users"
JSON Response Processing
#!/bin/bash
# Get user data and extract specific field
USER_NAME=$(curl -s https://jsonplaceholder.typicode.com/users/1 | \
python -c "import sys, json; print(json.load(sys.stdin)['name'])")
echo "User name: $USER_NAME"
Best Practices
Security Considerations
# Never expose sensitive data in scripts
# Bad
curl -H "Authorization: Bearer secret-token" https://api.example.com/users
# Good - Use environment variables
curl -H "Authorization: Bearer $API_TOKEN" https://api.example.com/users
# Better - Use credential files
curl -H "Authorization: Bearer $(cat ~/.api_token)" https://api.example.com/users
Performance Tips
# Use connection pooling
curl --keepalive-time 60 --keepalive-interval 60 https://api.example.com/users
# Compress requests when possible
curl -H "Accept-Encoding: gzip, deflate" https://api.example.com/users
# Cache responses when appropriate
curl -H "Cache-Control: max-age=3600" https://api.example.com/users
Error Handling
#!/bin/bash
# Check HTTP status code
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://api.example.com/users)
if [ $HTTP_CODE -eq 200 ]; then
echo "API call successful"
elif [ $HTTP_CODE -eq 401 ]; then
echo "Authentication failed"
elif [ $HTTP_CODE -eq 404 ]; then
echo "Resource not found"
else
echo "API call failed with status: $HTTP_CODE"
fi
Common curl Options Reference
Request Options
-X, --request # Specify HTTP method
-H, --header # Add header
-d, --data # Send data in POST request
-F, --form # Send form data
-u, --user # Basic authentication
-b, --cookie # Send cookies
Response Options
-o, --output # Save response to file
-i, --include # Include response headers
-I, --head # Show headers only
-v, --verbose # Show detailed information
-s, --silent # Silent mode (no progress bar)
-w, --write-out # Custom output format
Connection Options
--max-time # Maximum time for request
--retry # Number of retries
--retry-delay # Delay between retries
-k, --insecure # Allow insecure connections
-L, --location # Follow redirects
Conclusion
curl is an indispensable tool for API development, testing and debugging. Its command-line interface makes it perfect for automation, scripting and quick API testing without the overhead of graphical tools.
Mastering curl commands will significantly improve your API development workflow, allowing you to:
- Test APIs quickly from the command line
- Debug issues with detailed request/response information
- Automate testing through scripts and CI/CD pipelines
- Document APIs with working examples
- Troubleshoot problems in production environments
Start with the basic examples and gradually incorporate more advanced features as you become comfortable with the tool. Remember to use verbose mode (-v) when debugging and always test your curl commands before using them in scripts.