curl

2026.04.10

公式ドキュメント

この記事の要点

curl -X POST -dでAPIリクエスト、-Hでヘッダ追加
-fsSLの組み合わせがスクリプト利用の定番
-wオプションでレスポンスタイム計測やステータスコード取得が可能

概要

curl は URL を使ってデータを送受信する CLI ツールで、HTTP/HTTPS、FTP、SMTP などのプロトコルをサポートします。本チートシートは HTTP API の動作確認やスクリプト利用で頻出するオプションを、公式 man ページに沿って整理したものです。

基本

コマンド説明
curl URLGET リクエスト(ボディを標準出力)
curl -o file URL指定ファイルに保存
curl -O URLURL の末尾名で保存
curl -L URLリダイレクトを追跡
curl -I URLHEAD リクエスト(ヘッダのみ)
curl -i URLレスポンスヘッダ + ボディ
curl -v URL詳細ログ(送受信ヘッダ含む)
curl -s URLサイレント(進捗非表示)
curl -S URLサイレント時もエラーは表示
curl -f URLHTTP エラー時に非 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' URLGET のクエリとして送信
curl -T file URLPUT アップロード

ヘッダ

コマンド説明
curl -H 'Content-Type: application/json' URLヘッダ追加
curl -H 'Authorization: Bearer TOKEN' URL認可ヘッダ
curl -A 'Mozilla/5.0' URLUser-Agent
curl -e 'https://ref.example' URLReferer
curl -H 'Accept: application/json' URLAccept
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 URLBasic 認証
curl -u user URLパスワードは対話入力
curl --digest -u user:pass URLDigest 認証
curl --ntlm -u user:pass URLNTLM 認証
curl --negotiate -u : URLKerberos/SPNEGO
curl -H 'Authorization: Bearer TOKEN' URLBearer Token
curl --oauth2-bearer TOKEN URLOAuth2 Bearer
コマンド説明
curl -b 'k=v' URLCookie 送信
curl -b cookies.txt URLファイルから送信
curl -c cookies.txt URLCookie をファイルに保存
curl -b in.txt -c out.txt URLセッション継続
curl -j URLCookie Jar を使用(セッション)

注意: -u user:passはプロセス一覧に見えるため、本番環境では.netrcや環境変数を使いましょう。

プロキシ・TLS

コマンド説明
curl -x http://proxy:8080 URLHTTP プロキシ
curl --socks5 host:1080 URLSOCKS5 プロキシ
curl -k URLTLS 証明書検証を無効化(検証用途のみ)
curl --cacert ca.pem URLCA を指定
curl -E cert.pem --key key.pem URLクライアント証明書
curl --tlsv1.3 URLTLS 最低バージョン
curl --resolve example.com:443:1.2.3.4 URLDNS を手動指定

HTTP/2・HTTP/3

コマンド説明
curl --http1.1 URLHTTP/1.1 を強制
curl --http2 URLHTTP/2 を使用
curl --http3 URLHTTP/3 を使用(ビルド要)

ファイルアップロード

コマンド説明
curl -F 'file=@photo.jpg' URLmultipart/form-data
curl -F 'file=@photo.jpg;type=image/jpeg' URLMIME 指定
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 URLURL の名前で保存
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 -# -T big.bin https://example.com/upload/

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 設定ファイルを使う

# ~/.curlrc
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--formmultipart フィールド
-u--user認証情報
-o--output出力ファイル
-O--remote-nameリモート名で保存
-L--locationリダイレクト追跡
-I--headHEAD
-i--includeヘッダ込み出力
-v--verbose詳細表示
-s--silentサイレント
-S--show-errorエラーのみ表示
-f--failHTTP エラー時に失敗終了
-k--insecureTLS 検証無効
-A--user-agentUser-Agent
-b--cookieCookie 送信
-c--cookie-jarCookie 保存

トラブルシューティング

状況原因 / 対処
curl: (6) Could not resolve hostDNS 解決失敗。ネットワーク・/etc/hosts--resolve を確認
curl: (7) Failed to connectTCP 接続失敗。ポート・ファイアウォールを確認
curl: (35) SSL connect errorTLS ネゴ失敗。--tlsv1.2 等で調整
curl: (60) SSL certificate problemCA が無い。--cacert を指定(-k は検証用のみ)
400 Bad RequestContent-Type やボディ構文を確認
401/403トークン失効・権限不足
リダイレクト先に行かない-L を追加
POST なのに空になる-d @file@ や URL エンコードを確認

Tips

  • 秘密情報を -u user:pass で渡すとプロセス一覧に見える。環境変数・.netrc を活用する。
  • ~/.netrcmachine host login u password p を書くと自動で認証される。
  • curl -v の出力で > は送信行、< は受信行、* はメタ情報。
  • JSON 系では Content-TypeAccept を明示すると再現性が高い。
  • スクリプト内では必ず -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 内のブレース/ブラケット展開順に対応します。

再利用可能なシェル関数例

# JSON POST ヘルパ
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-Typecurl の指定
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 '^(\*|<)'

# 特定の CA バンドルで検証
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_FILECA バンドルのパス
SSLKEYLOGFILETLS キーログ(Wireshark 用)
CURL_CA_BUNDLECA バンドルのデフォルトパス
CURL_SSL_BACKEND使用する TLS バックエンド
NETRC.netrc の代替パス
HOME設定ファイル探索のベース

よくある書式変数の組合せ

# API レイテンシ計測
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塾です。

メールで無料相談する
← 一覧に戻る