Coldfusionから外部API(chttp)へのリクエスト関数サンプル

cf

目次

APIの運用環境や仕様は様々です。関数的なタイプで引数をポストでリクエストするタイプもあれば、ヘッダー情報に必要な定義やパラメーターをセットしてGETでリクエストし、結果セットをJSON、Array(配列)、Struct(構造体)、クエリ、バイナリ形式で取得するなどのケースが考えられます。

Coldfusionでは多様な外部APIの環境や形式に合わせたリクエスト関数の作成が可能ですが、ここでは、curlリクエストに基づいて、cfhttpを使用した関数のサンプルを作成してみます。

curlリクエスト

curl https://url/paymentMethods \
-H "x-API-key: YOUR_X-API-KEY" \
-H "content-type: application/json" \
-d '{
  "merchantAccount": "YOUR_MERCHANT_ACCOUNT",
  "countryCode": "NL",
  "amount": {
    "currency": "EUR",
    "value": 1000
  },
  "channel": "Web"
}'

cfhttpを実行する関数を作成

try{
    apiKey = 'myKey';
    requestURL = 'https://url/';
    merchantAccount = 'myAccount';
    amount = {
      'value': 1000,
      'currency': 'USD'  
    };
    cfhttp(method="GET", url="#requestURL#/paymentMethods", result="data"){
        cfhttpparam(name="x-API-key", type="header", value="#apiKey#");
        cfhttpparam(name="content-type", type="header", value="application/json");
        cfhttpparam(name="merchantAccount", type="formfield", value="#merchantAccount#");
        cfhttpparam(name="countryCode", type="formfield", value="US");
        cfhttpparam(name="amount", type="formfield", value="#amount#");
        cfhttpparam(name="channel", type="formfield", value="web");
    }
    data = deserializeJSON(data);
    WriteDump(data);
} catch(any e){
    WriteDump(e);
}
Facebook
Twitter
Pinterest