Excited to see this in Spring '24, I spent time today writing some Apex for Sandboxes to update the named credentials - URLs, usernames, passwords - for non-prod systems after a sandbox refresh.
Every integrated system needs a good solid solution for updating named credentials in non-prod environments. Seems like a great fit!
Here's what I found:
- updateNamedCredential is in the Connect REST Api, and it works well from Postman to update the Named Credential URL and label - see the Salesforce API postman collection for details on this PUT request.
- But..is not exposed in Apex. So we cannot update a named credential URL in Apex.
- ConnectApi.NamedCredentials.createNamedCredential is exposed. I can programatially create a named credential. I created one dynamically based on the sandbox URL, which I should then be able to use as the named credential to a callout back to the sandbox to use the REST Api for the update. Cool.
- But... calloutStatus is not exposed to Apex like it is in the REST Api, so it's always created as Disabled - unable to be used for callouts. Ok, let's manually mark this as active for now - later we'll rebuild this against the REST Api where we can set status to Enabled.
- Ok, with that manual work around in place I replicated my postman PUT call to update the named credential URL in Apex. Created and debug the body of the message. It matches. URL matches. Authorization matches. Method matches.
- Salesforce rejects the callout from Apex: 400 [{"errorCode":"INVALID_API_INPUT","message":"Specify a request body."}] .
- There is a body.
- debugging req.getBody() proves that to be the case.
- Salesforce rejects the same as if I set no body.
- Salesforce rejects the callout from Apex: 400 [{"errorCode":"INVALID_API_INPUT","message":"Specify a request body."}] .
Does anyone see what I'm doing wrong here?
I may pick this up again later, but for now it seems like there's no path forward for updating named credential URLs or renaming from Apex; I don't see a path forward for the use case of updating named credentials to point to non-prod systems in sandboxes.
CC: @Ross Belmont
Yes, that is all correct. The create and (future) update will leave the credential in a disabled state, requiring an admin to toggle it to the enabled state.
FYI if you create credentials any other way *besides* Apex, the toggle is
Enabled. It's only credentials created by managed packages that might not
be trustworthy and require admin review/intervention. An admin would have
created all other credentials.