Using curl to Test APIs
Introduction
Section titled “Introduction”curl is a versatile command-line tool used to send HTTP requests. Developers and system administrators often use it to test APIs, download files, and debug network issues. This guide walks through common tasks with curl.
Prerequisites
Section titled “Prerequisites”- A Linux or macOS system (Ubuntu typically has curl preinstalled).
- Basic familiarity with HTTP requests.
Send a Simple GET Request
Section titled “Send a Simple GET Request”curl https://api.github.com/users/octocatThis fetches a JSON object containing details for the GitHub user octocat.
Add Headers
Section titled “Add Headers”Include an authorization header when accessing APIs:
curl -H "Authorization: Bearer $TOKEN" https://api.example.com/dataPOST Data
Section titled “POST Data”Send a JSON payload to an API endpoint:
curl -X POST -H "Content-Type: application/json" \-d '{"name":"test","value":42}' \https://api.example.com/submitSave Output to a File
Section titled “Save Output to a File”curl -o response.json https://api.github.com/users/octocatPretty-print JSON with jq (Optional)
Section titled “Pretty-print JSON with jq (Optional)”Combine curl with jq for readable JSON output:
curl https://api.github.com/users/octocat | jq .Automating with a Script
Section titled “Automating with a Script”Save multiple curl calls in a shell script (test-api.sh):
#!/bin/bashcurl -s https://api.example.com/health | jq .curl -s -H "Authorization: Bearer $TOKEN" https://api.example.com/data | jq .Run with:
bash test-api.sh