この記事の要点
• curl -X POST -dでAPIリクエスト、-Hでヘッダ追加
• -fsSLの組み合わせがスクリプト利用の定番
• -wオプションでレスポンスタイム計測やステータスコード取得が可能
概要
curl は URL を使ってデータを送受信する CLI ツールで、HTTP/HTTPS、FTP、SMTP などのプロトコルをサポートします。本チートシートは HTTP API の動作確認やスクリプト利用で頻出するオプションを、公式 man ページに沿って整理したものです。
基本
| コマンド | 説明 |
|---|
curl URL | GET リクエスト(ボディを標準出力) |
curl -o file URL | 指定ファイルに保存 |
curl -O URL | URL の末尾名で保存 |
curl -L URL | リダイレクトを追跡 |
curl -I URL | HEAD リクエスト(ヘッダのみ) |
curl -i URL | レスポンスヘッダ + ボディ |
curl -v URL | 詳細ログ(送受信ヘッダ含む) |
curl -s URL | サイレント(進捗非表示) |
curl -S URL | サイレント時もエラーは表示 |
curl -f URL | HTTP エラー時に非 0 終了 |
ポイント: 最も使う基本オプションは-v(詳細ログ)、-s(サイレント)、-L(リダイレクト追跡)の3つ。まずこれを覚えましょう。
メソッドとボディ
| コマンド | 説明 |
|---|
curl -X POST URL | メソッドを指定 |
curl -d 'a=1&b=2' URL | フォーム送信(POST) |
curl -d @body.json URL | ファイル内容を送信 |
curl --data-raw '...' | そのまま送信(@ を展開しない) |
curl --data-binary @file | バイナリ送信 |
curl --data-urlencode 'q=hello world' | URL エンコード |
curl -G -d 'q=hello' URL | GET のクエリとして送信 |
curl -T file URL | PUT アップロード |
ヘッダ
| コマンド | 説明 |
|---|
curl -H 'Content-Type: application/json' URL | ヘッダ追加 |
curl -H 'Authorization: Bearer TOKEN' URL | 認可ヘッダ |
curl -A 'Mozilla/5.0' URL | User-Agent |
curl -e 'https://ref.example' URL | Referer |
curl -H 'Accept: application/json' URL | Accept |
curl -H 'X-Header;' URL | 空ヘッダ送信(; を末尾に) |
curl -H 'Host:' URL | ヘッダ削除 |
注意: -dオプションはデフォルトでapplication/x-www-form-urlencodedとして送信されます。JSON を送るときは必ず-H 'Content-Type: application/json'を付けましょう。
認証
| コマンド | 説明 |
|---|
curl -u user:pass URL | Basic 認証 |
curl -u user URL | パスワードは対話入力 |
curl --digest -u user:pass URL | Digest 認証 |
curl --ntlm -u user:pass URL | NTLM 認証 |
curl --negotiate -u : URL | Kerberos/SPNEGO |
curl -H 'Authorization: Bearer TOKEN' URL | Bearer Token |
curl --oauth2-bearer TOKEN URL | OAuth2 Bearer |
Cookie
| コマンド | 説明 |
|---|
curl -b 'k=v' URL | Cookie 送信 |
curl -b cookies.txt URL | ファイルから送信 |
curl -c cookies.txt URL | Cookie をファイルに保存 |
curl -b in.txt -c out.txt URL | セッション継続 |
curl -j URL | Cookie Jar を使用(セッション) |
注意: -u user:passはプロセス一覧に見えるため、本番環境では.netrcや環境変数を使いましょう。
プロキシ・TLS
| コマンド | 説明 |
|---|
curl -x http://proxy:8080 URL | HTTP プロキシ |
curl --socks5 host:1080 URL | SOCKS5 プロキシ |
curl -k URL | TLS 証明書検証を無効化(検証用途のみ) |
curl --cacert ca.pem URL | CA を指定 |
curl -E cert.pem --key key.pem URL | クライアント証明書 |
curl --tlsv1.3 URL | TLS 最低バージョン |
curl --resolve example.com:443:1.2.3.4 URL | DNS を手動指定 |
HTTP/2・HTTP/3
| コマンド | 説明 |
|---|
curl --http1.1 URL | HTTP/1.1 を強制 |
curl --http2 URL | HTTP/2 を使用 |
curl --http3 URL | HTTP/3 を使用(ビルド要) |
ファイルアップロード
| コマンド | 説明 |
|---|
curl -F 'file=@photo.jpg' URL | multipart/form-data |
curl -F 'file=@photo.jpg;type=image/jpeg' URL | MIME 指定 |
curl -F 'name=Ada' -F 'file=@a.pdf' URL | 複数フィールド |
curl -F 'json=<meta.json;type=application/json' | ファイル内容を値として |
curl -T file sftp://host/path/ | SFTP アップロード |
ダウンロード
| コマンド | 説明 |
|---|
curl -O URL | URL の名前で保存 |
curl -o name URL | 指定名で保存 |
curl -C - -O URL | レジューム |
curl --limit-rate 200k URL | 帯域制限 |
curl -r 0-1023 URL | バイトレンジ取得 |
curl --parallel -O URL1 -O URL2 | 並列ダウンロード |
curl --retry 5 --retry-delay 2 URL | リトライ |
curl --max-time 30 URL | 全体タイムアウト |
curl --connect-timeout 5 URL | 接続タイムアウト |
実践メモ: -k(TLS検証無効)は開発環境でのみ使用してください。本番環境では--cacertで正しいCA証明書を指定するのが安全です。
実用スニペット集
1. JSON を POST
curl -X POST https://api.example.com/users \
-H 'Content-Type: application/json' \
-d '{"name":"Ada","age":30}'
2. 認証付き API 呼び出し
curl -H "Authorization: Bearer $TOKEN" \
-H 'Accept: application/json' \
https://api.example.com/me
3. レスポンスを jq で整形
curl -s https://api.github.com/repos/curl/curl | jq '.stargazers_count'
4. ステータスコードだけ取得
curl -o /dev/null -s -w '%{http_code}\n' https://example.com
5. 詳細タイミング計測
curl -o /dev/null -s -w \
'dns=%{time_namelookup} connect=%{time_connect} ttfb=%{time_starttransfer} total=%{time_total}\n' \
https://example.com
6. リダイレクト先の URL を取得
curl -o /dev/null -s -w '%{url_effective}\n' -L https://example.com
7. フォームログイン → セッション維持
curl -c jar.txt -d 'user=ada&pass=secret' https://example.com/login
curl -b jar.txt https://example.com/dashboard
8. GraphQL リクエスト
curl -X POST https://api.example.com/graphql \
-H 'Content-Type: application/json' \
-d '{"query":"{ me { id name } }"}'
9. 大きなファイルをアップロード(進捗表示)
curl -
10. ヘッダとボディを別ファイルへ
curl -D head.txt -o body.html https://example.com
11. Bearer トークンを環境変数から
TOKEN=$(cat ~/.token)
curl -H "Authorization: Bearer $TOKEN" https://api.example.com/secure
12. curl 設定ファイルを使う
user-agent = "my-agent/1.0"
silent
location
13. 複数 URL 一括取得
curl -O 'https://example.com/file[1-5].txt'
curl -O 'https://example.com/{a,b,c}/index.html'
14. POST で JSON ファイルを送る
curl -X POST -H 'Content-Type: application/json' \
--data @payload.json https://api.example.com/import
15. 実行するだけで失敗判定する CI 用
curl -fsSL https://example.com/script.sh | bash
ポイント: -w(write-out)オプションはパフォーマンス計測の必須ツール。%{time_starttransfer}でTTFB、%{time_total}で全体時間を取得できます。
書式変数(-w)早見表
| 変数 | 説明 |
|---|
%{http_code} | HTTP ステータス |
%{url_effective} | 最終 URL |
%{content_type} | Content-Type |
%{size_download} | 受信バイト数 |
%{size_upload} | 送信バイト数 |
%{speed_download} | 受信速度 |
%{time_namelookup} | DNS 解決時間 |
%{time_connect} | TCP 接続時間 |
%{time_appconnect} | TLS ハンドシェイク時間 |
%{time_starttransfer} | TTFB |
%{time_total} | 全体時間 |
%{num_redirects} | リダイレクト回数 |
オプション早見表
| 短 | 長 | 説明 |
|---|
-X | --request | メソッド |
-H | --header | ヘッダ追加 |
-d | --data | リクエストボディ |
-F | --form | multipart フィールド |
-u | --user | 認証情報 |
-o | --output | 出力ファイル |
-O | --remote-name | リモート名で保存 |
-L | --location | リダイレクト追跡 |
-I | --head | HEAD |
-i | --include | ヘッダ込み出力 |
-v | --verbose | 詳細表示 |
-s | --silent | サイレント |
-S | --show-error | エラーのみ表示 |
-f | --fail | HTTP エラー時に失敗終了 |
-k | --insecure | TLS 検証無効 |
-A | --user-agent | User-Agent |
-b | --cookie | Cookie 送信 |
-c | --cookie-jar | Cookie 保存 |
トラブルシューティング
| 状況 | 原因 / 対処 |
|---|
curl: (6) Could not resolve host | DNS 解決失敗。ネットワーク・/etc/hosts・--resolve を確認 |
curl: (7) Failed to connect | TCP 接続失敗。ポート・ファイアウォールを確認 |
curl: (35) SSL connect error | TLS ネゴ失敗。--tlsv1.2 等で調整 |
curl: (60) SSL certificate problem | CA が無い。--cacert を指定(-k は検証用のみ) |
| 400 Bad Request | Content-Type やボディ構文を確認 |
| 401/403 | トークン失効・権限不足 |
| リダイレクト先に行かない | -L を追加 |
| POST なのに空になる | -d @file の @ や URL エンコードを確認 |
Tips
- 秘密情報を
-u user:pass で渡すとプロセス一覧に見える。環境変数・.netrc を活用する。
~/.netrc に machine host login u password p を書くと自動で認証される。
curl -v の出力で > は送信行、< は受信行、* はメタ情報。
- JSON 系では
Content-Type と Accept を明示すると再現性が高い。
- スクリプト内では必ず
-fsSL のいずれかを状況に応じて付ける。
--next を使うと 1 コマンドで複数リクエストを連続実行できる。
実践メモ: ブラウザの「コピー as cURL」で得たコマンドをそのまま実行・修正できます。デバッグの起点として非常に便利です。
.netrc の活用
~/.netrc に認証情報を書いておくと、curl は該当ホストに対して自動で認証を付けます(.netrc 形式の仕様: https://everything.curl.dev/usingcurl/netrc)。
machine api.example.com
login alice
password s3cret
chmod 600 ~/.netrc
curl --netrc https://api.example.com/me
複数リクエストを 1 コマンドで(—next)
curl https://api.example.com/a \
--next -X POST -d '{"x":1}' https://api.example.com/b \
--next -H "Authorization: Bearer $T" https://api.example.com/c
ファイル名テンプレート(-o)
curl 'https://example.com/img/[001-010].png' -o 'img_#1.png'
curl 'https://example.com/{en,ja,fr}/index.html' -o '#1.html'
#1, #2 は URL 内のブレース/ブラケット展開順に対応します。
再利用可能なシェル関数例
jpost() {
local url="$1"; shift
curl -fsS -X POST "$url" \
-H 'Content-Type: application/json' \
-H "Authorization: Bearer $API_TOKEN" \
-d "$@"
}
dlretry() {
curl -fL --retry 5 --retry-delay 2 --retry-max-time 60 \
--continue-at - -O "$1"
}
実運用での比較: curl と他ツール
| 用途 | curl の強み | 備考 |
|---|
| API 動作確認 | どこでも動く、フラグが豊富 | jq との組合せが定番 |
| ダウンロード | レジューム、並列、帯域制限 | wget -c と同等以上 |
| CI スクリプト | -fsSL で厳格化しやすい | 依存追加不要 |
| 計測 | -w でタイミング取得 | ab/hey の代わりにも |
Content-Type とボディの組み合わせ
| Content-Type | curl の指定 |
|---|
application/json | -H 'Content-Type: application/json' -d '{...}' |
application/x-www-form-urlencoded | -d 'a=1&b=2' または --data-urlencode |
multipart/form-data | -F 'field=value' -F 'file=@path' |
text/plain | -H 'Content-Type: text/plain' --data-binary @file |
application/xml | -H 'Content-Type: application/xml' -d @body.xml |
プロトコル別の基本例
FTP
curl ftp://ftp.example.com/ -u user:pass
curl -T upload.bin ftp://ftp.example.com/dir/ -u user:pass
SFTP / SCP
curl -u user: --key ~/.ssh/id_rsa sftp://host/path/file
curl -u user: -T local.txt scp://host/remote/path/
SMTP(メール送信)
curl --ssl-reqd smtp://smtp.example.com:587 \
--mail-from from@example.com \
--mail-rcpt to@example.com \
--upload-file mail.txt \
-u from@example.com:pass
WebSocket(7.86+)
curl --include --no-buffer \
--header "Connection: Upgrade" \
--header "Upgrade: websocket" \
--header "Sec-WebSocket-Key: $(openssl rand -base64 16)" \
--header "Sec-WebSocket-Version: 13" \
https://example.com/ws
HTTPS 証明書の調査
curl -vI https://example.com 2>&1 | grep -E '^(\*|<)'
curl --cacert /path/to/ca.pem https://internal.example
echo | openssl s_client -connect example.com:443 -servername example.com \
| openssl x509 > server.pem
デバッグのコツ
-v で始めて、--trace-ascii debug.txt で詳細を取る。
-w '\nHTTP %{http_code}\n' を末尾に付けてステータスを確実に出す。
- 再現性のあるコマンドを
--libcurl out.c で C コードとして出力できる。
- ブラウザの「コピー as cURL」で得たコマンドをそのまま実行・修正できる。
CURL_HOME や --config file で設定を切り替えると環境ごとの差異を吸収しやすい。
環境変数
| 変数 | 説明 |
|---|
http_proxy / https_proxy | プロキシ URL |
no_proxy | プロキシを使わないホスト |
CURL_HOME | .curlrc を探すディレクトリ |
SSL_CERT_FILE | CA バンドルのパス |
SSLKEYLOGFILE | TLS キーログ(Wireshark 用) |
CURL_CA_BUNDLE | CA バンドルのデフォルトパス |
CURL_SSL_BACKEND | 使用する TLS バックエンド |
NETRC | .netrc の代替パス |
HOME | 設定ファイル探索のベース |
よくある書式変数の組合せ
curl -o /dev/null -s \
-w 'code=%{http_code} ttfb=%{time_starttransfer}s total=%{time_total}s\n' \
https://api.example.com/health
curl -o /dev/null -s \
-w 'upload=%{size_upload} download=%{size_download}\n' \
-X POST -d @body.json https://api.example.com/ingest
参考リソース
この技術を体系的に学びたいですか?
未来学では東証プライム上場企業のITエンジニアが24時間サポート。月額24,800円から、退会金0円のオンラインIT塾です。
メールで無料相談する
← 一覧に戻る