この文章は Salesforce 機械翻訳システムを使用して翻訳されました。詳細はこちらをご参照ください。
英語に切り替える

Apex REST の基本コードサンプル

このサンプルでは、3 つの異なる HTTP 要求メソッドを処理する簡単な REST API を Apex に実装する方法を示します。cURL による認証についての詳細は、『REST API 開発者ガイド』「クイックスタート」セクションを参照してください。
  1. インスタンスに Apex クラスを作成します。そのためには、[設定] から、[クイック検索] ボックスに「新規」と入力し、[新規] を選択して次のコードを新しいクラスに追加します。
    1@RestResource(urlMapping='/Account/*')
    2global with sharing class MyRestResource {
    3
    4    @HttpDelete
    5    global static void doDelete() {
    6        RestRequest req = RestContext.request;
    7        RestResponse res = RestContext.response;
    8        String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
    9        Account account = [SELECT Id FROM Account WHERE Id = :accountId];
    10        delete account;
    11    }
    12  
    13    @HttpGet
    14    global static Account doGet() {
    15        RestRequest req = RestContext.request;
    16        RestResponse res = RestContext.response;
    17        String accountId = req.requestURI.substring(req.requestURI.lastIndexOf('/')+1);
    18        Account result = [SELECT Id, Name, Phone, Website FROM Account WHERE Id = :accountId];
    19        return result;
    20    }
    21  
    22  @HttpPost
    23    global static String doPost(String name,
    24        String phone, String website) {
    25        Account account = new Account();
    26        account.Name = name;
    27        account.phone = phone;
    28        account.website = website;
    29        insert account;
    30        return account.Id;
    31    }
    32}
  2. クライアントから doGet メソッドをコールするには、コマンドラインウィンドウを開き、次の cURL コマンドを実行して ID で取引先を取得します。
    curl -H "Authorization: Bearer sessionId" "https://instance.salesforce.com/services/apexrest/Account/accountId"
    • sessionId を、ログイン応答でメモした <sessionId> 要素に置き換えます。
    • instance<serverUrl> 要素に置き換えます。
    • accountId を、組織に存在する取引先の ID に置き換えます。

    doGet メソッドをコールすると、Salesforce が次のようなデータを伴う JSON 応答を返します。

    1{
    2  "attributes" : 
    3    {
    4      "type" : "Account",
    5      "url" : "/services/data/v22.0/sobjects/Account/accountId"
    6    },
    7  "Id" : "accountId",
    8  "Name" : "Acme"
    9
    10}

    このセクションの cURL の例では、名前空間による Apex クラスを使用していないため、URL に名前空間は含まれません。

    メモ

  3. 次のステップで作成する取引先のデータを含めるための account.txt というファイルを作成します。
    1{
    2  "name" : "Wingo Ducks",
    3  "phone" : "707-555-1234",
    4  "website" : "www.wingo.ca.us"
    5}
  4. コマンドラインウィ��ドウを使用して、次の cURL コマンドを実行し、新しい取引先を作成します。

    curl -H "Authorization: Bearer sessionId" -H "Content-Type: application/json" -d @account.txt "https://instance.salesforce.com/services/apexrest/Account/"

    doPost メソッドをコールすると、Salesforce が次のようなデータを伴う応答を返します。

    1"accountId"

    accountId は、POST 要求で作成した取引先の ID です。

  5. コマンドラインウィンドウを使用して、次の cURL コマンドを実行し、ID の指定によって取引先を削除します。

    curl —X DELETE —H "Authorization: Bearer sessionId" "https://instance.salesforce.com/services/apexrest/Account/accountId"