1

I am having issues giving an API key to an external url for a rest callout.

req.setHeader is where I attempt to do so. How should I structure this? I only get 401 unauth errors.

I am trying to authenticate using the CampaignMonitor API via an API Key.

https://www.campaignmonitor.com/api/getting-started/#grab-a-wrapper

public class HttpCallOut {

    public string getJSONResponse(String url) {

        Http h = new Http();

        HttpRequest req = new HttpRequest();

        req.setEndpoint(url);
        req.setMethod('GET');

        // Set Api Key
        req.setHeader('Authorization', 'Bearer a5p4dkey382apikey3382nns21jsskeyi29');

        HttpResponse res = h.send(req);

        system.debug(res);
        return res.getBody();

    } 
}
  • You said you are using the API Key method, but you are clearly using the OAuth access token method. Refer 'Authenticating with an API key' section in the link you provided. – Avinash Oct 23 '17 at 19:17
  • @Avinash I do not think I can do a curl from apex? – Cressida Oct 23 '17 at 19:19
  • Then you will have to follow the OAuth process...Create a connected app, generate access token by calling api.createsend.com/oauth/token and use it in the setHeader. – Avinash Oct 23 '17 at 19:27
0

cURL is not supported by Apex so you will need to follow the OAuth flow. Please refer to the docs here REST API Docs and recheck your information for the API for Campaign Monitor and set your application up to use OAuth appropriately

0
  1. Go to campaign monitor
  2. the API key from the Account Settings page when logged into your Campaign Monitor account.
  3. Below is the code for cURL and Apex that will help you get started. Note that this uses BASIC authentication, not oAuth. The header construction is the major difference here.

your curl will look like this curl -u "YOURAPIKEY:x" https://api.createsend.com/api/v3.2/clients.json?pretty=true

Here is the code to call from apex

String username = 'YOURAPIKEY';

String password = 'x';  
Blob headerValue = Blob.valueOf(username + ':' + password);
String authorizationHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);


Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('https://api.createsend.com/api/v3.2/clients.json'); //update this for your actual query
req.setMethod('GET');
req.setHeader('Authorization', authorizationHeader);
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');


HttpResponse res = h.send(req);
System.debug(res);
System.debug(res.getBody());
System.debug(res.getStatusCode());

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.