401 unauthorize status response on Rest API POST Call

I am working to run GET and POST call setup for Salesforce using Katalon. I successfully got the Token and passed it to the GET method that take the Record Id and bring back the JSON response. This is all working fine. Now when i run the POST call i am getting the 401 Unauthorize error message and i was not able to resolve it. Here is my code for the POST call and its response.

class CRUDOperation {

	final static String queryPath = "/services/data/v49.0/query/";
	final static CloseableHttpClient httpclient = HttpClients.createDefault();
	final static ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
	private static String REST_ENDPOINT = "/services/data" ;
	private static String API_VERSION 	= "/v49.0" ;
	public static Map<String, String> SFTokenandInstanceURL;
	public static String SFDCId;
	public static String instanceUrl, accessToken ;
	public static JSONObject leadDataAPI = new JSONObject();
	private static Map<String, String> lead = new HashMap<String, String>()
	public  static Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");
	private static Header oauthHeader;
	private static leadId;



	public static JSONObject createLead() throws Exception {


		SFTokenandInstanceURL = GetSFToken.getSFToken();
		instanceUrl = (String) SFTokenandInstanceURL.get("instanceURL");
		accessToken = (String) SFTokenandInstanceURL.get("accessToken");
		
		//This is fake data
		String leadId 	= null;
		String firstName = "John" ;
		String lastName	= "Zolensky";
		String email = "John.Zolensky@icbm.com";
		String city = "Chicago";
		String postalcode = "61616" ;
		String state	= "Illinois";
		String mobilephone = "1773219087";
		String phone = "3134520098";
		String title	= "Developer";
		String website = "www.icbm.com";
		String street = "9873 N Pima Rd";
		String company = "Somoto";

		try {
			lead.put("FirstName", firstName);
			lead.put("LastName", lastName);
			lead.put("Email", email);
			lead.put("City", city);
			lead.put("PostalCode", postalcode);
			lead.put("State", state);
			lead.put("MobilePhone", mobilephone);
			lead.put("Phone", phone);
			lead.put("Title", title);
			lead.put("Website", website);
			lead.put("Street", street);
			lead.put("Company", company)
			}
		catch (JSONException e) {
			e.printStackTrace();throw new ServletException(e);
		}

		HttpPost httpost = new HttpPost(instanceUrl+ REST_ENDPOINT+ API_VERSION +"/sobjects/Lead");
		httpost.addHeader("Authorization", "OAuth" + accessToken);
		StringEntity messageEntity = new StringEntity( lead.toString(), ContentType.create("application/json"));
		httpost.setEntity(messageEntity);


		// Execute the request.
		CloseableHttpResponse  closeableresponse = httpclient.execute(httpost);
		
		println("Response Status line :" + closeableresponse.getStatusLine());

		try {

			println("HTTP status : " + closeableresponse.getStatusLine().getStatusCode());

			if (closeableresponse.getStatusLine().getStatusCode()  == HttpStatus.SC_CREATED) {

				try {

					System.out.println("Record created successfully and here is the Response.............\n\n ");
					
					// Do the needful with entity.
					HttpEntity entity = closeableresponse.getEntity();
					InputStream rstream = entity.getContent();
					JSONObject authResponse = new JSONObject(new JSONTokener(rstream));

					println("Create response: " + authResponse.toString(2));

					if (authResponse.getBoolean("success")) {
						leadId = authResponse.getString("id");
						println("New record id " + leadId + "\n\n");
						leadDataAPI.put("leadSFDCId", leadId);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		finally {
			httpclient.close();
		}

		return leadDataAPI;
	}

}



RESPONSE:
2024-09-15 22:12:18.908 INFO  c.k.katalon.core.main.TestCaseExecutor   - --------------------
2024-09-15 22:12:18.912 INFO  c.k.katalon.core.main.TestCaseExecutor   - START Test Cases/Test
2024-09-15 22:12:19.281 DEBUG testcase.Test                            - 1: salesforceAPI.CRUDOperation.createLead()

Response Status line :HTTP/1.1 401 Unauthorized
HTTP status : 401
2024-09-15 22:12:22.711 INFO  k.k.c.m.CustomKeywordDelegatingMetaClass - salesforceAPI.CRUDOperation.createLead is PASSED
2024-09-15 22:12:22.726 INFO  c.k.katalon.core.main.TestCaseExecutor   - END Test Cases/Test
 

1 Like

Hi there, :wave:

Thank you very much for your topic! It may take a little while before Katalon team member or others forum members respond to you.

In the meantime, you can double-check your post to see if you can add any extra information i.e. error logs, HTML codes, screenshots, etc. Check out this posting guide to help us help you better!

Thanks! :sunglasses:
Katalon Community team

Hi @newyorktominnesota,

Welcome to our community. Looking forward to hearing from the experienced to support this case

does POST call working locally?

have you added all required headers and tokens to authenticate and authorise the POST call?

I have added bunch of print statements to make sure it prints out the important info e.g. token, http req etc.

2024-09-19 00:46:45.499 INFO  c.k.katalon.core.main.TestCaseExecutor   - --------------------
2024-09-19 00:46:45.502 INFO  c.k.katalon.core.main.TestCaseExecutor   - START Test Cases/Test
2024-09-19 00:46:45.831 DEBUG testcase.Test                            - 1: salesforceAPI.CRUDOperation.createLead()


Access Token: 	
00D5Bfn1H8zfO7HggXaSFemI43p!ARQAQJLATkCNoYagshYchoz9UFqfHjpycDF4Dri9vW7ARUi667r9B447Mro9O.HH_sWGAnRngty5Bfn1H8zfO7HggX_mkmKE
Lead Data: 	
[Company:Somoto, Email:John.Zolensky@icbm.com, FirstName:John, State:Illinois, Phone:3134520098, PostalCode:61616, Title:Developer, Website:www.icbm.com, Street:9873 N Pima Rd, LastName:Zolensky, City:Chicago, MobilePhone:1773219087]


Entity Message: 	
[Content-Type: application/json,Content-Length: 233,Chunked: false]


HTTP Request: 	
POST https://playful-otter-1o15gi-dev-ed.my.salesforce.com/services/data/v49.0/sobjects/Lead HTTP/1.1


Response Status line :HTTP/1.1 401 Unauthorized
HTTP status : 401
2024-09-19 00:46:48.485 INFO  k.k.c.m.CustomKeywordDelegatingMetaClass - salesforceAPI.CRUDOperation.createLead is PASSED
2024-09-19 00:46:48.498 INFO  c.k.katalon.core.main.TestCaseExecutor   - END Test Cases/Test

is it failing only with katalon API tests?

can you try with postman or curl commands?

Authorization error… can you check you swagger or API docs about API specifications