cURL

GitHub概要

curl/curl

A command line tool and library for transferring data with URL syntax, supporting DICT, FILE, FTP, FTPS, GOPHER, GOPHERS, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, MQTT, POP3, POP3S, RTMP, RTMPS, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET, TFTP, WS and WSS. libcurl offers a myriad of powerful features

ホームページ:https://curl.se/
スター38,346
ウォッチ785
フォーク6,782
作成日:2010年3月18日
言語:C
ライセンス:Other

トピックス

cclientcurlftpgopherhacktoberfesthttphttpsimapsldaplibcurllibrarymqttpop3scpsftptransfer-datatransferring-datauser-agentwebsocket

スター履歴

curl/curl Star History
データ取得日時: 2025/7/18 01:38

API開発ツール

cURL

概要

cURL(シーユーアールエル)は、最も基本的なコマンドラインHTTPクライアントです。ほぼすべてのシステムに標準搭載され、自動化やスクリプトで広く使用されています。基盤ツールとして不動の地位を維持し、新しいAPIツールが登場しても参照実装として重要な役割を果たし続けています。

詳細

cURLは、URL構文を使用してデータ転送を行うコマンドラインツールおよびライブラリです。HTTP、HTTPS、FTP、FTPS、SCP、SFTP、SMTP、LDAP、MQTTなど30以上のプロトコルをサポートし、Web技術の基盤として30年以上にわたって開発され続けています。最新安定版は8.14.1(2025年6月4日リリース)です。HTTPスクリプティングの分野では、Webからの情報自動抽出、ユーザーシミュレーション、Webサーバーへのデータ投稿・アップロードなど、現代の重要タスクを支えています。認証機能では、Basic、Digest、NTLM、Negotiate、Kerberosなど幅広い方式に対応し、最も安全な方式を自動選択する機能も提供します。設定ファイル(.curlrc)による自動化サポート、詳細なCookie管理、プロキシ対応、TLS/SSL暗号化により、エンタープライズ環境でも安心して利用できます。バッチ処理とスクリプティングに最適化された設計により、CI/CDパイプライン、監視システム、自動化スクリプトで不可欠な存在となっています。シンプルかつ強力なコマンド体系により、一度覚えれば長期間使い続けられる投資効果の高いツールです。

メリット・デメリット

メリット

  • 普遍的な存在: ほぼ全てのシステムに標準インストール済み
  • 豊富なプロトコル: HTTP/HTTPS以外に30以上のプロトコル対応
  • 完全な認証サポート: Basic、Digest、NTLM、Kerberos等に対応
  • 自動化に最適: スクリプトとバッチ処理での利用に特化
  • 軽量高速: 最小限のリソースで高いパフォーマンス
  • 設定ファイル対応: .curlrcによる自動化とカスタマイズ
  • プロキシ完全対応: HTTP、SOCKS4、SOCKS5プロキシサポート
  • 無料・オープンソース: 長期間安定したライセンス
  • 実績と信頼性: 30年以上の開発実績と広範な採用

デメリット

  • GUI不足: コマンドライン専用で視覚的インターフェースなし
  • 学習コスト: 豊富な機能ゆえにオプションが複雑
  • 出力が基本的: レスポンスの可視化や整形機能が限定的
  • 設定管理: 複雑な設定の管理が面倒な場合
  • デバッグ困難: エラー時のトラブルシューティングが困難

参考ページ

書き方の例

基本的なHTTPリクエスト

# 基本的なGETリクエスト
curl https://api.example.com/users

# ヘッダーを含むGETリクエスト
curl -H "Authorization: Bearer token123" \
     -H "Accept: application/json" \
     https://api.example.com/users

# POSTリクエストでJSONデータ送信
curl -X POST \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer token123" \
     -d '{"name":"田中太郎","email":"[email protected]","age":30}' \
     https://api.example.com/users

# PUTリクエスト
curl -X PUT \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer token123" \
     -d '{"name":"田中花子","active":true}' \
     https://api.example.com/users/123

# DELETEリクエスト
curl -X DELETE \
     -H "Authorization: Bearer token123" \
     https://api.example.com/users/123

認証方法

# Basic認証
curl -u username:password https://api.example.com/protected

# Basic認証(パスワード入力プロンプト)
curl -u username https://api.example.com/protected

# Bearer Token認証
curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
     https://api.example.com/profile

# APIキー認証(ヘッダー)
curl -H "X-API-Key: your-api-key-here" \
     https://api.example.com/data

# APIキー認証(クエリパラメータ)
curl "https://api.example.com/search?q=example&api_key=your-api-key"

# Digest認証
curl --digest -u username:password \
     https://api.example.com/digest-protected

# .netrcファイルからの自動認証
# ~/.netrc に認証情報を設定
cat ~/.netrc
# machine api.example.com
# login myusername  
# password mypassword

curl https://api.example.com/auto-auth

# .netrcを無視
curl --netrc-optional https://api.example.com/protected

データの送信とファイル操作

# JSONファイルからデータ送信
curl -X POST \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer token123" \
     -d @user-data.json \
     https://api.example.com/users

# ファイルアップロード(multipart/form-data)
curl -X POST \
     -H "Authorization: Bearer token123" \
     -F "[email protected]" \
     -F "title=重要な文書" \
     -F "category=documents" \
     https://api.example.com/upload

# バイナリファイルの送信
curl -X POST \
     -H "Content-Type: application/octet-stream" \
     -H "Authorization: Bearer token123" \
     --data-binary @image.png \
     https://api.example.com/upload/binary

# レスポンスをファイルに保存
curl -o response.json \
     -H "Authorization: Bearer token123" \
     https://api.example.com/data

# レスポンスをファイルに保存(リモートファイル名を使用)
curl -O \
     -H "Authorization: Bearer token123" \
     https://api.example.com/files/report.pdf

# 大きなファイルのダウンロード(プログレスバー表示)
curl -# -o large-file.zip \
     https://example.com/downloads/large-file.zip

詳細な出力とデバッグ

# レスポンスヘッダーのみ表示
curl -I https://api.example.com/health

# ヘッダーとボディを両方表示
curl -i -H "Authorization: Bearer token123" \
     https://api.example.com/users

# 詳細なデバッグ情報表示
curl -v -H "Authorization: Bearer token123" \
     https://api.example.com/users

# 非常に詳細なトレース情報
curl --trace-ascii trace.log \
     -H "Authorization: Bearer token123" \
     https://api.example.com/users

# リクエスト時間の測定
curl -w "Total time: %{time_total}s\nConnect time: %{time_connect}s\nHTTP code: %{http_code}\n" \
     -o /dev/null -s \
     https://api.example.com/performance

# JSONレスポンスの整形(jqと組み合わせ)
curl -s -H "Authorization: Bearer token123" \
     https://api.example.com/users | jq '.'

# 複数のURLを並行処理
curl -s https://api.example.com/endpoint1 & \
curl -s https://api.example.com/endpoint2 & \
curl -s https://api.example.com/endpoint3 & \
wait

プロキシとネットワーク設定

# HTTPプロキシ使用
curl --proxy http://proxy.example.com:8080 \
     https://api.example.com/data

# 認証付きプロキシ
curl --proxy http://user:[email protected]:8080 \
     https://api.example.com/data

# SOCKS5プロキシ
curl --socks5-hostname proxy.example.com:1080 \
     https://api.example.com/data

# SSL証明書検証をスキップ(テスト環境用)
curl -k https://self-signed.example.com/api

# カスタムCA証明書を使用
curl --cacert /path/to/ca-bundle.crt \
     https://secure.example.com/api

# クライアント証明書認証
curl --cert client.pem --key client.key \
     https://secure.example.com/api

# DNSサーバーを指定
curl --dns-servers 8.8.8.8,8.8.4.4 \
     https://api.example.com/data

# リダイレクトに従う
curl -L https://api.example.com/redirect-endpoint

# 最大リダイレクト回数を制限
curl -L --max-redirs 5 \
     https://api.example.com/redirect-endpoint

Cookie管理とセッション

# Cookieを保存
curl -c cookies.txt \
     -d "username=user&password=pass" \
     https://example.com/login

# 保存したCookieを使用
curl -b cookies.txt \
     https://example.com/protected-page

# Cookie付きでAPIリクエスト
curl -H "Authorization: Bearer token123" \
     -b "session=abc123; preferences=dark_mode" \
     https://api.example.com/user/settings

# セッション管理(ログインからAPI呼び出しまで)
# Step 1: ログイン
curl -c session-cookies.txt \
     -d "username=testuser&password=testpass" \
     https://example.com/api/login

# Step 2: APIアクセス(セッションCookie使用)
curl -b session-cookies.txt \
     https://example.com/api/profile

# Step 3: ログアウト
curl -b session-cookies.txt \
     -X POST https://example.com/api/logout

自動化とスクリプト統合

#!/bin/bash
# API監視スクリプト例

API_ENDPOINT="https://api.example.com/health"
API_KEY="your-api-key-here"
LOG_FILE="/var/log/api-monitor.log"

# ヘルスチェック関数
check_api_health() {
    local response_code
    local response_time
    
    response_code=$(curl -s -o /dev/null \
                         -w "%{http_code}" \
                         -H "X-API-Key: $API_KEY" \
                         --max-time 30 \
                         "$API_ENDPOINT")
    
    response_time=$(curl -s -o /dev/null \
                         -w "%{time_total}" \
                         -H "X-API-Key: $API_KEY" \
                         --max-time 30 \
                         "$API_ENDPOINT")
    
    echo "$(date): HTTP $response_code, Time: ${response_time}s" >> "$LOG_FILE"
    
    if [ "$response_code" != "200" ]; then
        echo "API Error: HTTP $response_code at $(date)" | \
        mail -s "API Alert" [email protected]
    fi
}

# 設定ファイル(.curlrc)の例
cat > ~/.curlrc << 'EOF'
# デフォルト設定
silent
show-error
location
max-time = 30
user-agent = "API-Monitor/1.0"
header = "Accept: application/json"
EOF

# JSONデータ処理とエラーハンドリング
api_call_with_retry() {
    local url="$1"
    local data="$2"
    local max_retries=3
    local retry_count=0
    
    while [ $retry_count -lt $max_retries ]; do
        response=$(curl -s -w "\n%{http_code}" \
                       -X POST \
                       -H "Content-Type: application/json" \
                       -H "Authorization: Bearer $API_TOKEN" \
                       -d "$data" \
                       "$url")
        
        http_code=$(echo "$response" | tail -n1)
        response_body=$(echo "$response" | sed '$d')
        
        if [ "$http_code" = "200" ] || [ "$http_code" = "201" ]; then
            echo "$response_body" | jq '.'
            return 0
        else
            echo "Attempt $((retry_count + 1)) failed: HTTP $http_code"
            retry_count=$((retry_count + 1))
            sleep 2
        fi
    done
    
    echo "API call failed after $max_retries attempts"
    return 1
}

# 使用例
check_api_health

api_call_with_retry "https://api.example.com/users" \
    '{"name":"テストユーザー","email":"[email protected]"}'

高度な設定とパフォーマンス

# 並行リクエスト制限とレート制限
for i in {1..10}; do
    curl -s -H "Authorization: Bearer token123" \
         "https://api.example.com/data?page=$i" \
         -o "page_$i.json" &
    
    # 毎秒最大5リクエストに制限
    if [ $((i % 5)) -eq 0 ]; then
        sleep 1
    fi
done
wait

# HTTP/2を強制使用
curl --http2 -H "Authorization: Bearer token123" \
     https://api.example.com/data

# Keep-Aliveを有効にして複数リクエスト
curl --keepalive-time 60 \
     -H "Authorization: Bearer token123" \
     https://api.example.com/endpoint1 \
     https://api.example.com/endpoint2 \
     https://api.example.com/endpoint3

# タイムアウト設定の詳細制御
curl --connect-timeout 10 \
     --max-time 30 \
     --retry 3 \
     --retry-delay 5 \
     --retry-max-time 120 \
     -H "Authorization: Bearer token123" \
     https://api.example.com/slow-endpoint

# IPv4/IPv6を明示的に指定
curl -4 https://api.example.com/ipv4-only
curl -6 https://api.example.com/ipv6-capable

# 帯域制限
curl --limit-rate 100k \
     -o large-download.zip \
     https://example.com/large-file.zip