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
Roy J 6Roy J 6 

Apex API Status:Method Not Allowed

When attempting to retrieve some information from an external API, I receive a "Status:Method Not Allowed" issue. However, the same API is working in Postman, where I am seeing the problem inside Apex. Would you kindly assist in finding a solution?

GET is the API method;
Body request: {"records":[ 493672139 ]}
Due to some reason, I couldn't provide the API details. Kindly share your thoughts

Apex code:
JSONGenerator gen = JSON.createGenerator(true);
List<integer> intlist = new List<integer>();
intlist.add(493672139);
gen.writeStartObject();
gen.writeFieldName('records');
gen.writeStartArray();
for (Integer record : intlist) {
    gen.writeNumber(record);
}
gen.writeEndArray();
gen.writeEndObject();
String pretty = gen.getAsString();
HttpRequest req = new HttpRequest();
Http http = new Http();
HttpResponse response = new HttpResponse();
req.setEndpoint("");
req.setMethod('GET');
req.setHeader('Content-Type', 'application/json');
req.setHeader('Authorization', '');
req.setBody(pretty);
req.setTimeout(90000);
response = http.send(req);

 

SubratSubrat (Salesforce Developers) 
Hello ,

The "Status: Method Not Allowed" issue in Apex could be due to multiple reasons. Here are some things to check and troubleshoot:

Check the API Endpoint: Ensure that the req.setEndpoint("") method is properly set with the correct API endpoint URL. Make sure there are no trailing spaces or incorrect characters in the URL. The API endpoint should be the same as the one that works in Postman.

Verify HTTP Method: Since you mentioned that the API method is "GET," it's essential to make sure that the correct method is set in the request using req.setMethod('GET').

Check Authorization Header: Ensure that the Authorization header is correctly set with the appropriate authentication token or credentials. This header might be required for authentication with the external API. Verify that the token or credentials are correct and valid for accessing the API.

Verify Request Body: Since this is a "GET" request, there should not be a request body. In your code, you have set the request body using the req.setBody(pretty), but GET requests typically do not include a request body. If the API requires parameters, they are usually passed as query parameters in the URL.

To fix this, remove the request body setup from your code for a "GET" request:
req.setBody(null); // Remove this line for a GET request
Verify SSL/TLS: Some APIs may require SSL/TLS encryption. Salesforce enforces TLS 1.2 or higher. Ensure that the API endpoint supports TLS 1.2 or higher.

Check CORS: If the API is on a different domain, verify that Cross-Origin Resource Sharing (CORS) is correctly configured to allow requests from Salesforce domains.

Hope this helps !
Thank you.