Create a simple .NET client
You can use this tutorial to create a client console application that consumes the Relativity REST API. It outlines key steps that you need to complete in order to retrieve Workspace and Document objects from Relativity. The sample client also illustrates how to authenticate, retrieve collections, and parse JSON representations for metadata. To download the complete code for this sample client, click here.
This page contains the following information:
- Before you begin
- Add directives for required namespaces
- Add the Main method
- Initialize an HttpClient instance and required headers
- Generate a basic authentication header
- Read a collection of Workspaces
- Parse the ArtifactID for a Workspace
- Retrieve a collection of Documents
- Determine the location of a Document
- Build and run the client
Before you begin
To create the sample client, complete the following tasks to set up your development environment:
- Confirm that you have the required software. See Set up a development environment.
- Create one or more Workspaces in your target Relativity instance, and add Documents to them. For this tutorial, make sure that the user has permissions only on these particular workspaces and that each of them contain Documents.
- Identify a user with access to one or more Workspaces in your target Relativity instance. In this sample client, the user is sample.user@relativity.com.
Note: You must provide a username and password when authenticating through the REST API. See REST API authentication and the client source code for more information.
- Create a console application in Visual Studio. See Set up a console application.
Add directives for required namespaces
To your application, add using directives referencing the namespaces that contain the classes used to work with HTTP and JSON. If these namespaces aren't available in your application, see Set up a console application.
1 2 3 4 5 6 7 | using System; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using Newtonsoft.Json.Linq; using System.Diagnostics.Contracts; |
Add the Main method
The sample client has a Main() method that includes the code for instantiating an HttpClient object that connects to the Relativity REST API. It also calls subsequent methods used to encode authentication credentials, retrieve Workspace and Document collections, and parse data from JSON.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | public static void Main( string [] args) { //Initialize the HttpClient. HttpClient client = new HttpClient(); //Add the Accept header. client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue( "application/json" )); //Generate a value for the Authorization header based on a specified //username and password. string authorizationHeaderValue = GenerateBasicAuthorizationParameter( "sample.user@relativity.com" , "UserPasswordHere" ); //Set the required headers for Relativity.REST. client.DefaultRequestHeaders.Add( "X-CSRF-Header" , "-" ); client.DefaultRequestHeaders.Add( "Authorization" , authorizationHeaderValue); //Read the Workspace collection. string workspaceCollectionString = GetWorkspaceCollectionAsString(client); //Get the Artifact ID for the first Workspace in the collection. int ? workspaceArtifactID = ParseWorkspaceArtifactIDFromWorkspaceCollectionString(workspaceCollectionString); //Get the __Location (URL) of the first Document in the Workspace. string firstDocumentUrl = null ; if (workspaceArtifactID.HasValue) { firstDocumentUrl = GetFirstDocumentUrlForWorkspace(client, workspaceArtifactID.Value); } Console.WriteLine( "The first Workspace's first Document Url {0} {1}" , string .IsNullOrEmpty(firstDocumentUrl) ? "could not be determined." : "is" , firstDocumentUrl); } |
Initialize an HttpClient instance and required headers
The sample client uses an HttpClient instance to send and receive HTTP messages through the Relativity REST API. You must instantiate an HttpClient object, and initialize it with a base address. This URI is the root level domain address where your target Relativity instance is hosted. See the following example:
1 2 3 4 | //Initialize the HttpClient. HttpClient client = new HttpClient(); |
In this client, the Relativity instance is hosted locally so the following addresses identify it:
- Instance address: http://localhost/Relativity
- BaseAddress: http://localhost/
- REST API address: http://localhost/Relativity.REST
Next, you need to set the X-CSRF-Header and Authorization headers, which are required by the Relativity REST API. The Authorization header is used to log in to the REST API when you submit a request.
1 2 3 4 | //Set the Relativity.REST required headers. client.DefaultRequestHeaders.Add( "X-CSRF-Header" , "-" ); client.DefaultRequestHeaders.Add( "Authorization" , authorizationHeaderValue); |
For more information, see HTTP headers.
Generate a basic authentication header
Since this sample client uses basic authentication, user credentials must be included in the Authorization field of the HTTP header. Base64 encoding is used here to encrypt the username and password added to the authentication header. This header also specifies the authorization method as Basic. For more information, see REST API authentication.
1 2 3 4 5 6 7 8 | static string GenerateBasicAuthorizationParameter( string username, string password) { string unencodedUsernameAndPassword = string .Format( "{0}:{1}" , username, password); byte [] unencodedBytes = ASCIIEncoding.ASCII.GetBytes(unencodedUsernameAndPassword); string base64UsernameAndPassword = System.Convert.ToBase64String(unencodedBytes); return string .Format( "Basic {0}" , base64UsernameAndPassword); } |
Read a collection of Workspaces
To read a collection of Workspaces, you can use the GetWorkspaceCollectionAsString() method provided in the sample code. This method assigns the following URL for a Workspace collection to a local variable:
1 | http: //localhost/Relativity.REST/Relativity/Workspace |
The URL is passed to the GetAsync() method on the HttpClient class to send a GET request as illustrated in this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 | static string GetWorkspaceCollectionAsString(HttpClient client) { string url = "Relativity.REST/Relativity/Workspace" ; HttpResponseMessage response = client.GetAsync(url).Result; if (response.IsSuccessStatusCode) { return response.Content.ReadAsStringAsync().Result; } Console.WriteLine( "The collection GET for Workspace failed." ); return null ; } |
The collection of Workspaces is returned as a JSON string. For more information, see Workspaces.
Parse the ArtifactID for a Workspace
The Relativity REST API returns a JSON representation that includes the ArtifactIDs of the Workspaces in the collection. The ArtifactID is a unique identifier for Workspaces and other objects in Relativity. When you want to retrieve or perform other tasks with objects in a specific Workspace, you need to provide this identifier in the URL or JSON representation for a request.
The following method illustrates how to parse the JSON to obtain the ArtifactID of the first Workspace in the collection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | static int ? ParseWorkspaceArtifactIDFromWorkspaceCollectionString( string workspaceCollection) { if ( string .IsNullOrEmpty(workspaceCollection)) { Console.WriteLine( "Could not parse Workspace collection string because it was null or empty." ); return null ; } //Turn the workspace collection string into a JObject and obtain the Results JArray. JObject jWorkspaceResult = JObject.Parse(workspaceCollection); JArray jWorkspaces = (jWorkspaceResult[ "Results" ] as JArray); //If the array of Workspaces contained data, attempt to parse the ArtifactID // of the first Workspace. if (jWorkspaces != null && jWorkspaces.Any()) { var firstWorkspace = jWorkspaces.First(); int ? workspaceArtifactId = ( int ?)firstWorkspace[ "Artifact ID" ]; if (!workspaceArtifactId.HasValue) { Console.WriteLine( "Could not find an 'Artifact ID' on the first Workspace." ); } return workspaceArtifactId; } Console.WriteLine(jWorkspaces != null ? "The Workspace collection is empty." : "The Workspace collection is missing or null." ); return null ; } |
Retrieve a collection of Documents
You can retrieve a collection of Documents in a Workspace by substituting the ArtifactID for the {WorkspaceArtifactID} token in the following URL:
http: //localhost/Relativity.REST/Workspace/{WorkspaceArtifactID}/Document |
This method illustrates how to retrieve the collection by passing in the ArtifactID for a Workspace. It also returns the URL for the first Document in the collection:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | static string GetFirstDocumentUrlForWorkspace(HttpClient client, int workspaceArtifactID) { string url = string .Format( "Relativity.REST/Workspace/{0}/Document" , workspaceArtifactID); HttpResponseMessage response = client.GetAsync(url).Result; if (response.IsSuccessStatusCode) { //Read the Documents collection, and parse out the Results JArray. string documents = response.Content.ReadAsStringAsync().Result; JObject jDocumentResult = JObject.Parse(documents); JArray jDocuments = (jDocumentResult[ "Results" ] as JArray); //If the array of Documents contained data, obtain the __Location of the first Document. if (jDocuments != null && jDocuments.Any()) { return GetUrlFromDocument(jDocuments.First()); } Console.WriteLine(jDocuments != null ? "The Document collection is empty." : "The Document collection is missing or null." ); } else { Console.WriteLine( "The collection GET for Documents failed." ); } return null ; } |
For more information, see Documents.
Determine the location of a Document
You can parse the URL for the document resource from its JSON representation that you retrieved with the GET method. This code sample illustrates how to return this string by parsing the JToken representing the Document object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | static string GetUrlFromDocument(JToken documentJToken) { if (documentJToken != null && documentJToken.Type == JTokenType.Object) { string url = ( string )((documentJToken as JObject)[ "__Location" ]); if ( string .IsNullOrWhiteSpace(url)) { Console.WriteLine( "The Document's __Location is missing or null." ); } return url; } Console.WriteLine(documentJToken != null ? string .Format( "The Document JTokenType is a '{0}' but should be a JObject." , documentJToken.Type) : "The Document JToken is null." ); return null ; } |
Build and run the client
You can download the complete source code for building and running the client in Visual Studio. To download the complete code for this sample client, click here.
Note: You need to update URLs, Workspace, and other references so that the sample client can run in your Relativity environment.