tyoshikawa1106のブログ

- Force.com Developer Blog -

SFDC:ApexとREST Callouts

TrailheadのApex SOAP Calloutsに載っていた内容についてです。

f:id:tyoshikawa1106:20160117153210p:plain

Apex REST Callouts Unit | Salesforce Trailhead


下記HerokuアプリにHTTPRequestを行うとJSON文字列が返ってきます。

https://th-apex-http-callout.herokuapp.com/animals/1

f:id:tyoshikawa1106:20160117152218p:plain


Apexの場合はこんな感じです。

public class AnimalLocator {
    
    public static String getAnimalNameById(Integer  prm) {
        // Request
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/' + prm);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        
        // Get Result
        String result = '';
        if (response.getStatusCode() == 200) {
            Map<String, Object> resultJSON = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            Map<String,Object> animal = (Map<String,Object>) resultJSON.get('animal');
            result = (String)animal.get('name');
        }
        
        return result;
    }
}


テストクラスを実装する際にはモッククラスを用意します。

@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"}}');
        response.setStatusCode(200);
        return response; 
    }
}


実際のテストクラスはこちら

@isTest
private class AnimalLocatorTest {

    @isTest static  void testGetAnimalNameById() {
        Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock()); 
        String result = AnimalLocator.getAnimalNameById(1);
        System.assertEquals(result, 'chicken');
    }
}


Apexから外部サイトにコールアウトする場合はリモートサイトの設定が必要です。
f:id:tyoshikawa1106:20160117152839p:plain


コードの細かい部分はちょっと雑にやっちゃいましたがこんな感じです。