0

I am using developer console and trying to create a new simple class so I can make an external callout to a REST api and return some json data. I've added the remote URL in the Remote Site settings in salesforce.

I put together this very minimal class, but when saving, I get errors related to my usage of request.setEndpoint and I'm not sure why. I also tried setting the URL to a variable of String type and then passing that into request.setEndPoint, but still does not work and I get errors.

public with sharing class RestTest {

    Http h = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndPoint('https://docsample.herokuapp.com/jsonSample');
    request.setHeader('Content-type', 'application/json');
    request.setMethod('GET');

    HttpResponse response = h.send(request);
}

In the "Problems" tab in developer console I see these errors:

Extra ')', at 'https://docsample.herokuapp.com/jsonSample'.

Expecting ')' but was: 'Content-type'

Extra ')', at 'GET'.

Method already defined: void RestTest.() from the type RestTest

1 Answer 1

0

Your code needs to be contained inside of a method. Variables like Http h and HttpRequest request can be declared and initialized outside of a method, but pretty much anything other than that needs to be inside a method.

Incorrect:

public with sharing class RestTest {

    Http h = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndPoint('https://docsample.herokuapp.com/jsonSample');
    request.setHeader('Content-type', 'application/json');
    request.setMethod('GET');

    HttpResponse response = h.send(request);
}

Correct:

public with sharing class RestTest {

    public void myCallout(){
        Http h = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndPoint('https://docsample.herokuapp.com/jsonSample');
        request.setHeader('Content-type', 'application/json');
        request.setMethod('GET');

        HttpResponse response = h.send(request);
    }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .