function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Yogesh BiyaniYogesh Biyani 

named credentials

I am currently using following apex code to check if the user exists in a discourse site. How do I set up the named credentials so that I remove the username/key from this code ?
HttpRequest req3 = new HttpRequest();
req3.setEndpoint('https://forumname/admin/users/list/all.json?&email=' + emailAddress);
req3.setMethod('GET');
req3.setHeader('api-username','myusername');
req3.setHeader('api-key','myapikey');

Http http3 = new Http();
HTTPResponse res3 = new HTTPResponse();

if (Test.isRunningTest() && (mock!=null)) {
res3 = mock.respond(req3);
} else {
res3= http3.send(req3);
} 

System.debug(res3.getBody().length());
if(res3.getBody().length()==2)
    System.debug('Discourse Not found');
else 
{
    System.debug(res3.getBody());
    System.debug('Discourse found ');   
    Discourse=true;
}

TIA
SwethaSwetha (Salesforce Developers) 
HI Yogesh,
If you want to remove un/Pwd, you can try this approach 

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);
Reference:https://salesforce.stackexchange.com/questions/217281/use-a-named-credential-with-api-key/217282

Test class for named credentials: https://salesforce.stackexchange.com/questions/75490/mock-testing-with-named-credentials

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you