Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Mastering `curl` on Linux: Downloads and API Requests

1 min read .
Mastering `curl` on Linux: Downloads and API Requests

curl is one of the most useful command-line tools for transferring data and testing HTTP APIs. It supports HTTP, HTTPS, FTP, and many other protocols, making it useful for downloads, automation, diagnostics, and API development.

1. Check or Install curl

Check the installed version:

curl --version

On Debian or Ubuntu:

sudo apt update
sudo apt install curl

Other distributions provide curl through their normal package managers.

2. Download Files

Save a remote file using the filename from the URL:

curl -O https://example.com/file.zip

If the URL redirects, add -L:

curl -LO https://example.com/file.zip

Choose your own output filename with lowercase -o:

curl -o custom-name.zip https://example.com/file.zip

Resume a partially downloaded file:

curl -C - -O https://example.com/file.zip

3. Inspect HTTP Responses

Request only the response headers:

curl -I https://example.com

For more diagnostic detail about the connection and request, use verbose mode:

curl -v https://example.com

4. Send Form Data

-d sends a request body and causes curl to use POST unless another method is specified:

curl -d "param1=value1&param2=value2" https://example.com/api

You normally do not need -X POST when using -d.

5. Send JSON

Modern curl versions support the convenient --json option:

curl --json '{"key":"value"}' https://example.com/api

A widely compatible equivalent is:

curl -H "Content-Type: application/json" \
  -d '{"key":"value"}' \
  https://example.com/api

6. Authentication

Basic authentication:

curl -u username https://example.com/private

curl will prompt for the password, which is preferable to putting a password directly in shell history.

Bearer token authentication:

curl -H "Authorization: Bearer YOUR_TOKEN" https://example.com/api

Avoid committing real tokens to scripts or repositories. Prefer environment variables or a secret-management system for automation.

7. Cookies and Redirects

Save cookies:

curl -c cookies.txt https://example.com

Send stored cookies:

curl -b cookies.txt https://example.com

Follow redirects:

curl -L https://example.com

8. Check an HTTP Status Code in a Script

#!/usr/bin/env bash
url="https://example.com"
status_code=$(curl -o /dev/null -sS -w "%{http_code}" "$url")
printf 'Status code: %s\n' "$status_code"

For scripts that should fail on HTTP errors, consider --fail or --fail-with-body depending on the behavior you need.

Conclusion

curl covers far more than simple downloads. With a small set of options you can inspect HTTP responses, send form or JSON data, authenticate to APIs, manage cookies, follow redirects, and automate health checks from the shell.

Related Posts

chevron-up