[SalesForce] Use a Named Credential with API key

I want to be able to make callouts to JotForm, but they do not support OAuth and username/password is insufficient for their API. Here are their docs; for reference, here are the 3 auth options:

  1. Authenticate with Query Parameters
  2. Authenticate with HTTP Headers
  3. Authenticate with Javascript SDK

Basically, they provide an API Key and want me to include an apikey parameter in the header. I don't want to hard code it, I don't want to store it as plain text in custom settings/metadata, and this isn't a managed package. Is there any way to securely store/authenticate from Salesforce, ideally using a Named Credential?

I'd love to be able to just have a Named Credential that is just a securely stored, obscured API Key…

Best Answer

Well... sort of. The only two officially supported methods are by Basic Authentication and OAuth tokens. That site uses a non-standard API design, so it can't directly benefit from using a Named Credential. "But wait," I hear you say, "you didn't say it wasn't possible." And for that, you'd be correct. Here's what we can do to work within this system's design.

First, go to the New Named Credential screen. Specify the base endpoint ("http://api.jotform.com/"), set the Identity Type to "Named Principle," choose Authentication Protocol "Password Authentication," specify any random user name ("anonymous" should work), and type in the API key as your password. Uncheck "Generate Authorization Header" and check "Allow Merge Fields in HTTP Header", then save this Named Credential.

Now, in your code, you can specify the API key using a merge field:

HttpRequest req = new HttpRequest();
req.setMethod('GET');
req.setEndpoint('callout:jotform/user');
req.setHeader('APIKEY', '{!$Credential.Password}');
HttpResponse res = new Http().send(req);
Related Topic