REST API Format for creating a Session using Basic Authentication
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-20-2018 12:21 AM
Hi,
I am trying to consume ServiceNow Rest API using JAVA and want to know the format of REST API format to create a session using Basic Authentication.
Any help will be much appreciated.
Thanks & Regards,
Darshit Kothari

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-20-2018 01:39 AM
Hi,
basic auth is nothing ServiceNow specific, but http specific and it always works like this:
https://username:password@www.example.com/
make sure you always user https for security reasons.
Best regards

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎07-20-2018 07:43 AM
Hi Darshkothari,
REST web services are stateless, so you're going to get a new session for every authenticated request sent to the instance. Basic Auth is when you pass in a base64 encoding of the username:password. If you have OAuth implemented, you can authenticate using a token as well. Here's a rough example of how you can use SN REST APIs with Basic Auth through Java:
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.io.IOException;
import java.io.OutputStream;
public class test {
public static void main(String[] args) throws MalformedURLException, IOException {
String urlString = "https://demoinstance.service-now.com/api/now/table/incident";
String userpass = "admin" + ":" + "password";
// Encode credentials with Base64
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setDoOutput(true);
httpConnection.setRequestMethod("POST");
httpConnection.setRequestProperty("Authorization", basicAuth);
httpConnection.setRequestProperty("Content-Type","application/json; charset=utf-8");
httpConnection.setRequestProperty("Host", "demoinstance.service-now.com");
OutputStream output = httpConnection.getOutputStream();
String payload = "{'short_description':'REST test','state':'2'}";
output.write(payload.getBytes());
int response = httpConnection.getResponseCode();
System.out.println(response);
}
}
I hope that's along the lines of what you were looking for. Best of luck!
-Brian