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
Felix Jong Seok ChaeFelix Jong Seok Chae 

URI for Inserting a new case via REST

I have a REST API in Java that tries to insert a new case record in SF.
HttpPost constructor takes URI string, which is formatted as baseUri + "/sobjects/case/".
I keep getting the message saying that insertion was unsuccessful. 
How can I find the correct URI to insert a new case record?
Raj VakatiRaj Vakati
Hi ,
Can you please share the error  ? You are doing correctly. 
URI :/services/data/v39.0/sobjects/Case
Method :POST 
Body:{
  "ContactId" : "0034100000bUywHAAS",
  "AccountId" : "0014100000TfIKBAA3",
  "BusinessHoursId" : "01m410000008RKiAAM",
  "Status" : "Closed",
  "Reason" : "Performance",
  "Origin" : "Phone",
  "Subject" : null,
  "Priority" : "Medium"
 
}


User-added image


 
Felix Jong Seok ChaeFelix Jong Seok Chae
// Create Cases using REST HttpPost
  public static void createCases() {
    System.out.println("\n_______________  INSERT _______________");
    String uri = baseUri + "/sobjects/Cases/"; // can't find uri for insertion
    try {

      //create the JSON object containing the new lead details.
      JSONObject sfcase = new JSONObject();
      sfcase.put("Description", "a new description was made for a new case.");

      System.out.println("JSON for case record to be inserted:\n" + sfcase.toString(1));

      //Construct the objects needed for the request
      HttpClient httpClient = HttpClientBuilder.create().build();

      HttpPost httpPost = new HttpPost(uri);
      httpPost.addHeader(oauthHeader);
      httpPost.addHeader(prettyPrintHeader);
      // The message we are going to post
      StringEntity body = new StringEntity(sfcase.toString(1));
      body.setContentType("application/json");
      httpPost.setEntity(body);

      //Make the request
      HttpResponse response = httpClient.execute(httpPost);

      //Process the results
      int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode == 201) {
        String response_string = EntityUtils.toString(response.getEntity());
        JSONObject json = new JSONObject(response_string);
        // Store the retrieved lead id to use when we update the lead.
        caseId = json.getString("id");
        System.out.println("New case id from response: " + caseId);
      } else {
        System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
      }
    } catch (JSONException e) {
      System.out.println("Issue creating JSON or processing results");
      e.printStackTrace();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    } catch (NullPointerException npe) {
      npe.printStackTrace();
    }
  }

_______________  INSERT _______________
JSON for case record to be inserted:
{"Description": "a new description was made for a new case."}
Insertion unsuccessful. Status code returned is 404

Process finished with exit code 0

Thank you.
Raj VakatiRaj Vakati
Hi Felix  ,

Is your authentication was successful?  can you please let me know 
Felix Jong Seok ChaeFelix Jong Seok Chae
Hi,
yes it was successful.

 
Raj VakatiRaj Vakati
Share the complete class 
Felix Jong Seok ChaeFelix Jong Seok Chae
package salesforce_rest;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONTokener;
import org.json.JSONException;

public class Modifier {

  static final String USERNAME     = "myusername";
  static final String PASSWORD     = "password + security token";
  static final String LOGINURL     = "sandbox url";
  static final String GRANTSERVICE = "/services/oauth2/token?grant_type=password";
  static final String CLIENTID     = "clientid";
  static final String CLIENTSECRET = "clientsecret";

  private static String REST_ENDPOINT = "/services/data" ;
  private static String API_VERSION = "/v32.0" ;
  private static String baseUri;
  private static Header oauthHeader;
  private static Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");
  private static String caseId ;


  // Connect REST API to SalesForce
  public static void main(String[] args) {

    HttpClient httpclient = HttpClientBuilder.create().build();

    // Assemble the login request URL
    String loginURL = LOGINURL +
        GRANTSERVICE +
        "&client_id=" + CLIENTID +
        "&client_secret=" + CLIENTSECRET +
        //"&redirect_uri=" + RedirectURI +
        "&username=" + USERNAME +
        "&password=" + PASSWORD;
    System.out.println(loginURL);
    // Login requests must be POSTs
    HttpPost httpPost = new HttpPost(loginURL);
    HttpResponse response = null;

    try {
      // Execute the login POST request
      response = httpclient.execute(httpPost);
    } catch (ClientProtocolException cpException) {
      cpException.printStackTrace();
    } catch (IOException ioException) {
      ioException.printStackTrace();
    }

    // verify response is HTTP OK
    final int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
      System.out.println("Error authenticating to Force.com: "+statusCode);
      // Error is in EntityUtils.toString(response.getEntity())
      return;
    }

    String getResult = null;
    try {
      getResult = EntityUtils.toString(response.getEntity());
    } catch (IOException ioException) {
      ioException.printStackTrace();
    }

    JSONObject jsonObject = null;
    String loginAccessToken = null;
    String loginInstanceUrl = null;

    try {
      jsonObject = (JSONObject) new JSONTokener(getResult).nextValue();
      loginAccessToken = jsonObject.getString("access_token");
      loginInstanceUrl = jsonObject.getString("instance_url");
    } catch (JSONException jsonException) {
      jsonException.printStackTrace();
    }

    baseUri = loginInstanceUrl + REST_ENDPOINT + API_VERSION ;
    oauthHeader = new BasicHeader("Authorization", "OAuth " + loginAccessToken) ;
    System.out.println("oauthHeader1: " + oauthHeader);
    System.out.println("\n" + response.getStatusLine());
    System.out.println("Successful login");
    System.out.println("instance URL: "+loginInstanceUrl);
    System.out.println("access token/session ID: "+loginAccessToken);
    System.out.println("baseUri: "+ baseUri);


    // Run codes to query, insert, update and delete records in Salesforce using REST API
    createCases();
    
    // release connection
    httpPost.releaseConnection();
  }

// Create Cases using REST HttpPost
  public static void createCases() {
    System.out.println("\n_______________  INSERT _______________");
    String uri = baseUri + "/sobjects/Cases/"; // can't find uri for insertion
    try {

      //create the JSON object containing the new lead details.
      JSONObject sfcase = new JSONObject();
      sfcase.put("Description", "a new description was made for a new case.");

      System.out.println("JSON for case record to be inserted:\n" + sfcase.toString(1));

      //Construct the objects needed for the request
      HttpClient httpClient = HttpClientBuilder.create().build();

      HttpPost httpPost = new HttpPost(uri);
      httpPost.addHeader(oauthHeader);
      httpPost.addHeader(prettyPrintHeader);
      // The message we are going to post
      StringEntity body = new StringEntity(sfcase.toString(1));
      body.setContentType("application/json");
      httpPost.setEntity(body);

      //Make the request
      HttpResponse response = httpClient.execute(httpPost);

      //Process the results
      int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode == 201) {
        String response_string = EntityUtils.toString(response.getEntity());
        JSONObject json = new JSONObject(response_string);
        // Store the retrieved lead id to use when we update the lead.
        caseId = json.getString("id");
        System.out.println("New case id from response: " + caseId);
      } else {
        System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
      }
    } catch (JSONException e) {
      System.out.println("Issue creating JSON or processing results");
      e.printStackTrace();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    } catch (NullPointerException npe) {
      npe.printStackTrace();
    }
  }
}

 
Raj VakatiRaj Vakati
please find the code here  and list of java jar for class path 
User-added image
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
 
public class Main {
 
	static final String USERNAME     = "aaa";
  static final String PASSWORD     = "aaa";
  static final String LOGINURL     = "https://login.salesforce.com";
  static final String GRANTSERVICE = "/services/oauth2/token?grant_type=password";
  static final String CLIENTID     = "CsA7Dtid8U3JBtA3sWm8Cz.h22aUDlZtkdew";
  static final String CLIENTSECRET = "asd";

private static String REST_ENDPOINT = "/services/data" ;
private static String API_VERSION = "/v32.0" ;
private static String baseUri;
private static Header oauthHeader;
private static Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");
    private static String leadId ;
    private static String leadFirstName;
    private static String leadLastName;
    private static String leadCompany;
 
    public static void main(String[] args) {
 
        HttpClient httpclient = HttpClientBuilder.create().build();
 
        // Assemble the login request URL
String loginURL = LOGINURL +
                  GRANTSERVICE +
                  "&client_id=" + CLIENTID +
  "&client_secret=" + CLIENTSECRET +
  "&username=" + USERNAME +
  "&password=" + PASSWORD;
 
        // Login requests must be POSTs
        HttpPost httpPost = new HttpPost(loginURL);
        HttpResponse response = null;
 
        try {
            // Execute the login POST request
            response = httpclient.execute(httpPost);
        } catch (ClientProtocolException cpException) {
            cpException.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
 
        // verify response is HTTP OK
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
    System.out.println("Error authenticating to Force.com: "+statusCode);
// Error is in EntityUtils.toString(response.getEntity())
            return;
        }
 
        String getResult = null;
        try {
            getResult = EntityUtils.toString(response.getEntity());
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
 
        JSONObject jsonObject = null;
        String loginAccessToken = null;
        String loginInstanceUrl = null;
 
        try {
            jsonObject = (JSONObject) new JSONTokener(getResult).nextValue();
            loginAccessToken = jsonObject.getString("access_token");
loginInstanceUrl = jsonObject.getString("instance_url");
        } catch (JSONException jsonException) {
            jsonException.printStackTrace();
        }
 
        baseUri = loginInstanceUrl + REST_ENDPOINT + API_VERSION ;
        oauthHeader = new BasicHeader("Authorization", "OAuth " + loginAccessToken) ;
System.out.println("oauthHeader1: " + oauthHeader);
System.out.println("\n" + response.getStatusLine());
System.out.println("Successful login");
System.out.println("instance URL: "+loginInstanceUrl);
System.out.println("access token/session ID: "+loginAccessToken);
System.out.println("baseUri: "+ baseUri);        
 

createCase();
        httpPost.releaseConnection();
    }
public static void createCase() {
    System.out.println("\n_______________ Case INSERT _______________");
 
        String uri = baseUri + "/sobjects/case/";
        try {
 
            //create the JSON object containing the new lead details.
JSONObject lead = new JSONObject();
lead.put("Description", "Hello world");
lead.put("Status", "New");
lead.put("Origin", "Web");
 
            System.out.println("JSON for lead record to be inserted:\n" + lead.toString(1));
 
            //Construct the objects needed for the request
            HttpClient httpClient = HttpClientBuilder.create().build();
 
            HttpPost httpPost = new HttpPost(uri);
            httpPost.addHeader(oauthHeader);
            httpPost.addHeader(prettyPrintHeader);
            // The message we are going to post
StringEntity body = new StringEntity(lead.toString(1));
body.setContentType("application/json");
            httpPost.setEntity(body);
 
            //Make the request
            HttpResponse response = httpClient.execute(httpPost);
 
            //Process the results
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 201) {
    String response_string = EntityUtils.toString(response.getEntity());
    JSONObject json = new JSONObject(response_string);
    // Store the retrieved lead id to use when we update the lead.
  String  caseId = json.getString("id");
System.out.println("New Case id from response: " + caseId);
} else {
    System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
    }
} catch (JSONException e) {
    System.out.println("Issue creating JSON or processing results");
            e.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (NullPointerException npe) {
            npe.printStackTrace();
        }
    }
  
 
    private static String getBody(InputStream inputStream) {
        String result = "";
try {
    BufferedReader in = new BufferedReader(
            new InputStreamReader(inputStream)
    );
    String inputLine;
    while ( (inputLine = in.readLine() ) != null ) {
        result += inputLine;
        result += "\n";
            }
            in.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        return result;
    }
}




 
Raj VakatiRaj Vakati
I haven't refactor the code 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class Main {

	static final String USERNAME = "aaa";
	static final String PASSWORD = "aaa";
	static final String LOGINURL = "https://login.salesforce.com";
	static final String GRANTSERVICE = "/services/oauth2/token?grant_type=password";
	static final String CLIENTID = "CsA7Dtid8U3JBtA3sWm8Cz.h22aUDlZtkdew";
	static final String CLIENTSECRET = "asd";

	private static String REST_ENDPOINT = "/services/data";
	private static String API_VERSION = "/v32.0";
	private static String baseUri;
	private static Header oauthHeader;
	private static Header prettyPrintHeader = new BasicHeader("X-PrettyPrint", "1");
	 

	public static void main(String[] args) {

		HttpClient httpclient = HttpClientBuilder.create().build();

		// Assemble the login request URL
		String loginURL = LOGINURL + GRANTSERVICE + "&client_id=" + CLIENTID + "&client_secret=" + CLIENTSECRET
				+ "&username=" + USERNAME + "&password=" + PASSWORD;

		// Login requests must be POSTs
		HttpPost httpPost = new HttpPost(loginURL);
		HttpResponse response = null;

		try {
			// Execute the login POST request
			response = httpclient.execute(httpPost);
		} catch (ClientProtocolException cpException) {
			cpException.printStackTrace();
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}

		// verify response is HTTP OK
		final int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != HttpStatus.SC_OK) {
			System.out.println("Error authenticating to Force.com: " + statusCode);
			// Error is in EntityUtils.toString(response.getEntity())
			return;
		}

		String getResult = null;
		try {
			getResult = EntityUtils.toString(response.getEntity());
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}

		JSONObject jsonObject = null;
		String loginAccessToken = null;
		String loginInstanceUrl = null;

		try {
			jsonObject = (JSONObject) new JSONTokener(getResult).nextValue();
			loginAccessToken = jsonObject.getString("access_token");
			loginInstanceUrl = jsonObject.getString("instance_url");
		} catch (JSONException jsonException) {
			jsonException.printStackTrace();
		}

		baseUri = loginInstanceUrl + REST_ENDPOINT + API_VERSION;
		oauthHeader = new BasicHeader("Authorization", "OAuth " + loginAccessToken);
		System.out.println("oauthHeader1: " + oauthHeader);
		System.out.println("\n" + response.getStatusLine());
		System.out.println("Successful login");
		System.out.println("instance URL: " + loginInstanceUrl);
		System.out.println("access token/session ID: " + loginAccessToken);
		System.out.println("baseUri: " + baseUri);

		createCase();
		httpPost.releaseConnection();
	}

	public static void createCase() {
		System.out.println("\n_______________ Case INSERT _______________");

		String uri = baseUri + "/sobjects/case/";
		try {

			// create the JSON object containing the new lead details.
			JSONObject lead = new JSONObject();
			lead.put("Description", "Hello world");
			lead.put("Status", "New");
			lead.put("Origin", "Web");

			System.out.println("JSON for lead record to be inserted:\n" + lead.toString(1));

			// Construct the objects needed for the request
			HttpClient httpClient = HttpClientBuilder.create().build();

			HttpPost httpPost = new HttpPost(uri);
			httpPost.addHeader(oauthHeader);
			httpPost.addHeader(prettyPrintHeader);
			// The message we are going to post
			StringEntity body = new StringEntity(lead.toString(1));
			body.setContentType("application/json");
			httpPost.setEntity(body);

			// Make the request
			HttpResponse response = httpClient.execute(httpPost);

			// Process the results
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 201) {
				String response_string = EntityUtils.toString(response.getEntity());
				JSONObject json = new JSONObject(response_string);
				// Store the retrieved lead id to use when we update the lead.
				String caseId = json.getString("id");
				System.out.println("New Case id from response: " + caseId);
			} else {
				System.out.println("Insertion unsuccessful. Status code returned is " + statusCode);
			}
		} catch (JSONException e) {
			System.out.println("Issue creating JSON or processing results");
			e.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} catch (NullPointerException npe) {
			npe.printStackTrace();
		}
	}

	private static String getBody(InputStream inputStream) {
		String result = "";
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
			String inputLine;
			while ((inputLine = in.readLine()) != null) {
				result += inputLine;
				result += "\n";
			}
			in.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		return result;
	}
}
Felix Jong Seok ChaeFelix Jong Seok Chae
I got the same error message. I didn't add jre system library jar in intellij and can it be the cause of this error?
Raj VakatiRaj Vakati
Can you set the path to those jar files ?
Go to File-> Project Structure-> Libraries and click green "+" to add the jar files 
Felix Jong Seok ChaeFelix Jong Seok Chae
I think I did for all jars except jre system library.

User-added image
Felix Jong Seok ChaeFelix Jong Seok Chae
Sorry, now the error message returns status code 400 instead of 404. If I change one line to /sobjects/cases instead of /sobjects/case, then error message contains status code 404.
Raj VakatiRaj Vakati
Can you share the debug logs ?
Felix Jong Seok ChaeFelix Jong Seok Chae
***Console:
HTTP/1.1 200 OK
Successful login
instance URL: https://cs9.salesforce.com
access token/session ID: deleted
baseUri: https://cs9.salesforce.com/services/data/v32.0

_______________ Case INSERT _______________
JSON for lead record to be inserted:
{
 "Status": "New",
 "Origin": "Web",
 "Description": "Hello world"
}
Insertion unsuccessful. Status code returned is 400

Process finished with exit code 0

*** Screenshot of debug
User-added image


 
Raj VakatiRaj Vakati
Can you share your connected APP setting from Salesforce? I am assuming you are setting up scopes to API 
Felix Jong Seok ChaeFelix Jong Seok Chae
Sure.

User-added image
Felix Jong Seok ChaeFelix Jong Seok Chae
Following the slide 21 in 
http://www.asagarwal.com/2401/step-by-step-guide-to-get-started-with-salesforce-rest-api-using-java
I changed a callback url to the one that appeared right after my login to sandbox and waited more than 10 minutes to be effective but still give me the same error message.
Felix Jong Seok ChaeFelix Jong Seok Chae
Thank Vakati for your help thus far. I figured it out. The problem was that I didn't fill all the required fields for the case record.