Im struggling a bit making a REST callout to a service that has a rather odd (in my experience) means of authenticating.

The service PayPoint API - Confirmation of Payee (you need to register before they show docs!) wants a subscription key, Ocp-Apim-Subscription-Key and API key x-api-key to be provided in the header. So a call looks like the image below.

enter image description here

I can form and send that no problems in a REST client but in Apex when I try and do something like the below its giving me a System.CalloutException: Attempt to use invalid header in request exception.

    String url = 'https://multipay-sandbox.azure-api.net/cop/v1/COPSingle'; 
    Http h = new Http();        
    // Instantiate a new HTTP request, specify the method 
    HttpRequest req = new HttpRequest();
    req.setHeader('Content-Type', 'application/json');
    req.setHeader('Ocp-Apim-Subscription-Key ', 'dsadasdsada');
    req.setHeader('x-api-key', 'dsadasdasd');
    String reqBody = '{"customerName": "'+customerName+'","bankAccount": '+bankAccountNo+'","sortcode": "'+sortcode+'","accountType": "'+accountType+'","secondaryReference": "'+buildingSocRef+'"}';
    system.debug('reqBody -->' + reqBody);
    HttpResponse res = h.send(req);

Looking at the class documentation it doesnt really state that one can't add headers like this, but exception not encouraging. Im pretty confident this is the only means of authenticating with this service.

Any thoughts on a possible approach greatly appreciated!

Update I attempted constructing a header auth sting like the below (based on this answer) and passing it in as basic auth but while the api call went out the service didn't recognise any credentials being supplied

String headerAuthString = '{"Ocp-Apim-Subscription-Key ": "XXX", "x-api-key": "XXX"}';        
String encodedAuthString = EncodingUtil.urlEncode(headerAuthString, 'UTF-8');
req.setHeader('Authorization', 'BASIC ' + encodedAuthString );

1 Answer 1


Sorry all this was my silly mistake.

You can indeed set custom headers as key value pairs, just not when they contain an illegal space as I had on req.setHeader('Ocp-Apim-Subscription-Key ', 'dsadasdsada')

Sorting to req.setHeader('Ocp-Apim-Subscription-Key', 'dsadasdsada') and its all good.

(Btw if I should delete this post now Ive fixed the typo please comment and Ill do so)

You must log in to answer this question.

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