Get User Example
Open the Legalesign GraphQL Explorer
note
If you don't yet have any legalesign.com credentials, go to the free trial page and sign up here
Create a Query
In order to get you going as quickly as possible, let's execute a query straight away and make sure that everything is working.
Past the following into the main query window.
query GetUser($id: ID!) {
user(id: $id) {
id
name
email
firstName
lastName
}
}
By default, if you call the user object without an id the information returned is your own.
Running this sample
This code will create a command line example that accepts a username, password and api userid, then returns the result of this query.
auth-example.js
const AWS = require('aws-sdk');
const fetch = require('node-fetch');
class LegalesignAuth {
constructor() {
// General purpose pool credentials
this.userPoolId = 'eu-west-2_NUPAjABy7';
this.clientId = '38kn0eb9mf2409t6mci98eqdvt';
this.region = 'eu-west-2';
this.cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider({
region: this.region
});
}
async getAccessToken(username, password) {
try {
const params = {
AuthFlow: 'USER_PASSWORD_AUTH',
ClientId: this.clientId,
AuthParameters: {
USERNAME: username,
PASSWORD: password
}
};
const result = await this.cognitoIdentityServiceProvider.initiateAuth(params).promise();
return result.AuthenticationResult.AccessToken;
} catch (error) {
throw new Error(`Authentication failed: ${error.message}`);
}
}
async makeGraphQLRequest(token, query) {
const response = await fetch('https://graphql.uk.legalesign.com/graphql', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({ query })
});
return response.json();
}
}
// Example usage
async function main() {
const [username, password, userid] = process.argv.slice(3);
if (!username || !password) {
console.error('Usage: node auth-example.js <username> <password>');
process.exit(1);
}
try {
const auth = new LegalesignAuth();
// Get access token
console.log('Getting access token...');
const token = await auth.getAccessToken(username, password);
// Test with a simple query
const query = `
query getUser {
user(id: {$userid}) {
id
firstName
lastName
email
}
}
`;
console.log('Making GraphQL request...');
const result = await auth.makeGraphQLRequest(token, query);
console.log('User info:', JSON.stringify(result, null, 2));
} catch (error) {
console.error('Error:', error.message);
}
}
if (require.main === module) {
main();
}
module.exports = LegalesignAuth;
Run the Example
node auth-example.js your-username your-password userid
Python Example
auth_example.py
import boto3
import requests
import json
import sys
class LegalesignAuth:
def __init__(self):
# General purpose pool credentials
self.user_pool_id = 'eu-west-2_NUPAjABy7'
self.client_id = '38kn0eb9mf2409t6mci98eqdvt'
self.region = 'eu-west-2'
self.cognito_client = boto3.client(
'cognito-idp',
region_name=self.region
)
def get_access_token(self, username, password):
try:
response = self.cognito_client.initiate_auth(
AuthFlow='USER_PASSWORD_AUTH',
ClientId=self.client_id,
AuthParameters={
'USERNAME': username,
'PASSWORD': password
}
)
return response['AuthenticationResult']['AccessToken']
except Exception as e:
raise Exception(f'Authentication failed: {str(e)}')
def make_graphql_request(self, token, query):
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {token}'
}
response = requests.post(
'https://graphql.uk.legalesign.com/graphql',
headers=headers,
json={'query': query}
)
return response.json()
def main():
if len(sys.argv) < 3:
print('Usage: python auth_example.py <username> <password> [userid]')
sys.exit(1)
username = sys.argv[1]
password = sys.argv[2]
userid = sys.argv[3] if len(sys.argv) > 3 else None
try:
auth = LegalesignAuth()
# Get access token
print('Getting access token...')
token = auth.get_access_token(username, password)
# Test with a simple query
user_id_param = f'(id: "{userid}")' if userid else ''
query = f"""
query myInfo {{
user{user_id_param} {{
id
firstName
lastName
email
}}
}}
"""
print('Making GraphQL request...')
result = auth.make_graphql_request(token, query)
print('User info:', json.dumps(result, indent=2))
except Exception as e:
print(f'Error: {str(e)}')
if __name__ == '__main__':
main()
Run the Python Example
pip install boto3 requests
python auth_example.py your-username your-password userid
C# Example
AuthExample.cs
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Amazon.CognitoIdentityProvider;
using Amazon.CognitoIdentityProvider.Model;
public class LegalesignAuth
{
private readonly string _userPoolId = "eu-west-2_NUPAjABy7";
private readonly string _clientId = "38kn0eb9mf2409t6mci98eqdvt";
private readonly string _region = "eu-west-2";
private readonly AmazonCognitoIdentityProviderClient _cognitoClient;
private readonly HttpClient _httpClient;
public LegalesignAuth()
{
_cognitoClient = new AmazonCognitoIdentityProviderClient(Amazon.RegionEndpoint.EUWest2);
_httpClient = new HttpClient();
}
public async Task<string> GetAccessTokenAsync(string username, string password)
{
try
{
var request = new InitiateAuthRequest
{
AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
ClientId = _clientId,
AuthParameters = new Dictionary<string, string>
{
["USERNAME"] = username,
["PASSWORD"] = password
}
};
var response = await _cognitoClient.InitiateAuthAsync(request);
return response.AuthenticationResult.AccessToken;
}
catch (Exception ex)
{
throw new Exception($"Authentication failed: {ex.Message}");
}
}
public async Task<JsonDocument> MakeGraphQLRequestAsync(string token, string query)
{
var request = new HttpRequestMessage(HttpMethod.Post, "https://graphql.uk.legalesign.com/graphql")
{
Headers =
{
{ "Authorization", $"Bearer {token}" }
},
Content = new StringContent(
JsonSerializer.Serialize(new { query }),
Encoding.UTF8,
"application/json"
)
};
var response = await _httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
return JsonDocument.Parse(content);
}
public void Dispose()
{
_cognitoClient?.Dispose();
_httpClient?.Dispose();
}
}
class Program
{
static async Task Main(string[] args)
{
if (args.Length < 2)
{
Console.WriteLine("Usage: dotnet run <username> <password> [userid]");
Environment.Exit(1);
}
string username = args[0];
string password = args[1];
string userid = args.Length > 2 ? args[2] : null;
using var auth = new LegalesignAuth();
try
{
// Get access token
Console.WriteLine("Getting access token...");
string token = await auth.GetAccessTokenAsync(username, password);
// Test with a simple query
string userIdParam = !string.IsNullOrEmpty(userid) ? $"(id: \"{userid}\")" : "";
string query = $@"
query myInfo {{
user{userIdParam} {{
id
firstName
lastName
email
}}
}}";
Console.WriteLine("Making GraphQL request...");
var result = await auth.MakeGraphQLRequestAsync(token, query);
Console.WriteLine($"User info: {result.RootElement.GetRawText()}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
Run the C# Example
First, create a new console project and add the required packages:
dotnet new console -n LegalesignExample
cd LegalesignExample
dotnet add package AWSSDK.CognitoIdentityProvider
dotnet add package System.Text.Json
dotnet run your-username your-password userid