PATCH request using Apex HttpRequest

I’m looking for a way to create an HttpRequest in Apex using a POST method. When I do it, I hit this error:

{
    "message": "HTTP Method 'POST' not allowed. Allowed are HEAD,GET,PATCH,DELETE",
    "errorCode": "METHOD_NOT_ALLOWED"
}

When I try to make a PATCH request (to update), there’s an exception appearing in the developer console:

FATAL_ERROR System.CalloutException: Invalid HTTP method: PATCH

Just to give a quick background, I’m trying to use Salesforce’s REST API from inside my Apex class to update an CurrencyType record. It’s working outside Salesforce (using curl for example).

Thanks.

Answer

Here is a working POST example…

    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v28.0/sobjects/CurrencyType/');
    req.setMethod('POST');
    req.setBody('{ "IsoCode" : "ADP", "DecimalPlaces" : 2, "ConversionRate" : 1, "IsActive" : "true" }');
    req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());
    req.setHeader('Content-Type', 'application/json');
    HttpResponse res = h.send(req);

Here is a working PATCH example..

    Http h = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint(URL.getSalesforceBaseUrl().toExternalForm() + '/services/data/v28.0/sobjects/CurrencyType/01Lb0000000TWoP?_HttpMethod=PATCH');
    req.setBody('{ "DecimalPlaces" : 2 }');
    req.setHeader('Authorization', 'OAuth ' + UserInfo.getSessionId());
    req.setHeader('Content-Type', 'application/json');
    req.setMethod('POST');
    HttpResponse res = h.send(req);

Note: The documentation for setMethod does not list ‘PATCH’ as a method, though it says ‘for example’, so its unclear if its saying its not supported or the documentation author just missed it out.

Fortunately you can override the Http method as a URL parameter as described here.

If you use an HTTP library that doesn’t allow overriding or setting an arbitrary HTTP method name, you can send a POST request and provide an override to the HTTP method via the query string parameter _HttpMethod. In the PATCH example, you can replace the PostMethod line with one that doesn’t use override: PostMethod m = new PostMethod(url + “?_HttpMethod=PATCH”);

Attribution
Source : Link , Question Author : jpmonette , Answer Author : Andrew Fawcett

Leave a Comment