Like what you see? Have a play with our trial version.

Error rendering macro 'rw-search'

null

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

REST services related to user administration are available here: https://developers.yellowfinbi.com/dev/api-docs/current/#tag/users

There are two main approaches to user synchronization, the difference between the approaches relates to when the user synchronization takes place:

...

Code Block
languagejava
titleJava
collapsetrue
Code Block
languagec#
titleC#
collapsetrue
Code Block
titleGo
collapsetrue
Code Block
languagejs
titleJavaScript
collapsetrue
Code Block
languagephp
titlePHP
collapsetrue
Code Block
languagepy
titlePython
collapsetrue

Creating a User

Create a new user by providing an array of user models to POST /api/admin/users createUserAdmin . Pass multiple user models to create multiple users simultaneously.

The following examples create a new user in various programming languages.

This Java Code example uses Apache HTTP Client and GSON for handling REST calls and JSON serialization.
Code Block
languagejava
titleJava
collapsetrue
package rest.code.examples;
package rest.code.examples;
import java.io.IOException;
import java.util.Random;
import org.apache.hc.client5.http.fluent.Content;
import org.apache.hc.client5.http.fluent.Request;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
 * CreateRetrieve a user using the Yellowfin REST API
 */
public class CreateAUserRetrieveAUser {
    public static void main(String[] args) throws Exception {

     
	    	String host = ""http://localhost:8080/YellowfinyellowfinHead"";
	        	String restUsername = ""admin@yellowfin.com.au"";
	        	String restPassword = ""test"";

	    	
	    	String createUserPayloaduserToRetrieve = "[ {" +
""admin@yellowfin.com.au"";
	    	
	    	String token = generateToken(host, restUsername, restPassword);
	    	
	  "  \"userId\": \"user1\",	System.out.println(""Retrieving User: "" + userToRetrieve);
	    	
	    	Content c =     Request.get(host + "  \"emailAddress\": \"user1@yellowfin.com.au\"," +
                "  \"roleCode\": \"Consumer & Collaborator\"," +
                "  \"password\": \"test\"," +
  "/api/rpc/users/user-details-by-username/"" + userToRetrieve)
	  	    		.addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong() + "", token="" + token)
	  	    		.addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
	  	    		.addHeader(""Content-Type"", ""application/json"")
	  	        .execute().returnContent();
	  	    "	
	  \"firstName\": \"User\"," +
  System.out.print(c.asString());
	 
   }
  
   public static String generateToken(String host, String username, "String  \"lastName\": \"One\"," +password) throws IOException {
   	
   	  	Content c = Request.post(host + ""/api/refresh-tokens"")
 	  "  \"languageCode\": \"EN\",		.addHeader(""Authorization"", ""YELLOWFIN ts="" +
 System.currentTimeMillis() + "" , nonce="" + new Random().nextLong())
 	       "  \"timeZoneCode\": \"AUSTRALIA/SYDNEY\"" +
                " } ]";




 		.addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
 	    		.addHeader(""Content-Type"", ""application/json"")
 	    		.bodyString(""{ \""userName\"": \""""+ username + ""\"",\""password\"": \""""+ password + ""\""}"", null)
 	       String token = generateToken(host, restUsername, restPassword .execute().returnContent();
 	    	
 	    JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
 	    JsonElement accessToken  System.out.println("Payload: " + createUserPayload= jsonObject.getAsJsonObject(""_embedded"").getAsJsonObject(""accessToken"").get(""securityToken"");
 	   
 	   Content cif (accessToken!= Request.post(host + "/api/admin/users")null) {
 	    		System.out.println(""Access Token: "" + accessToken);
 	    } else {
 	    		System.out.println(""Token not retrieved successfully"");
 	    		System.exit(-1);
 	    }
 	    return accessToken.getAsString();
   	
   }
  
}
Code Block
languagec#
titleC#
collapsetrue
namespace YellowfinAPIExamples;

using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class CreateAUserRetrieveAUser
{
    static async Task Main(string[] args)
    {
        string host = ""http://localhost:8080/YellowfinyellowfinHead"";
        string restUsername = ""admin@yellowfin.com.au"";
        string restPassword = ""test"";
        string userToRetrieve   = ""admin@yellowfin.com.au"";

        string createUserPayloadtoken = "[ {" +await GenerateToken(host, restUsername, restPassword);

        Console.WriteLine(""Retrieving User: "" + userToRetrieve);

        using (var httpClient = new HttpClient())
        {
  "  \"userId\": \"user1\"," +
      httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(""YELLOWFIN"", ""ts="" + DateTimeOffset.Now.ToUnixTimeMilliseconds() + "" , nonce="" + new Random().NextInt64() + "", token="" + token);
           "  \"emailAddress\": \"user1@yellowfin.com.au\"," + httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));

            HttpResponseMessage response = await httpClient.GetAsync(host + ""/api/rpc/users/user-details-by-username/"" + userToRetrieve);
            if (response.IsSuccessStatusCode)
  "  \"roleCode\": \"Consumer & Collaborator\"," +
    {
                string responseBody = await response.Content.ReadAsStringAsync();
           "  \"password\": \"test\"," +
  Console.WriteLine(responseBody);
            }
            else
            "{
  \"firstName\": \"User\"," +
            Console.WriteLine(""Failed to retrieve user details. Status code: "" + response.StatusCode);
            }
  "  \"lastName\": \"One\"," +
  }
    }
    
    static async Task<string> GenerateToken(string host, string restUsername, string restPassword)
    {
        using "(var  \"languageCode\": \"EN\"," +client = new HttpClient())
        {
            // Generate nonce
            long "nonce  \"timeZoneCode\": \"AUSTRALIA/SYDNEY\"" +
= new Random().NextInt64();
            
            // Create HTTP request
         " } ]";

 var request = new HttpRequestMessage(HttpMethod.Post, host  string token = await GenerateToken(host, restUsername, restPassword);

+ ""/api/refresh-tokens"");
            request.Headers.Add(""Authorization"",  Console.WriteLine("Payload: ""YELLOWFIN ts="" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + "", nonce="" + createUserPayloadnonce);

        using (HttpClient client = new HttpClient()) request.Headers.Add(""Accept"", ""application/vnd.yellowfin.api-v1+json"");
        {
    request.Content = new StringContent(
     long nonce = new Random().NextInt64();
       JsonConvert.SerializeObject(new { userName = restUsername, HttpRequestMessage requestpassword = new HttpRequestMessage(HttpMethod.Post, host + "/api/admi
Code Block
titleGo
collapsetrue
package main

import (
restPassword }),
         "bytes"
        "encodingMediaTypeHeaderValue.Parse(""application/json"")
        "fmt"
    );

         "io/ioutil"
   // Send request and get "math/rand"response
        "net/http"
    HttpResponseMessage response =  "time"
)

func main() {
await client.SendAsync(request);
            string hostresponseContent := "http://localhost:8080/Yellowfin" await response.Content.ReadAsStringAsync();

        restUsername := "admin@yellowfin.com.au"
  // Parse JSON response
   restPassword := "test"

       JObject createUserPayloadjsonObject := `[{JsonConvert.DeserializeObject<JObject>(responseContent);
            string accessToken =  "userId": "user1",jsonObject[""_embedded""][""accessToken""][""securityToken""].ToString();

                "emailAddress": "user1@yellowfin.com.au",if (!string.IsNullOrEmpty(accessToken))
                "roleCode": "Consumer & Collaborator",{
                Console.WriteLine("password"Access Token: "test",
" + accessToken);
            }
      "firstName": "User",
     else
           "lastName": "One", {
                Console.WriteLine("languageCode":Token not retrieved"EN",);
                "timeZoneCode": "AUSTRALIA/SYDNEY"
        }]`

        token, err := generateToken(host, restUsername, restPassword)Environment.Exit(-1);
        if err != nil {}

                fmt.Println("Error generating token:", err)return accessToken;
        }
        return
        }

        fmt.Println("Payload:", createUserPayload)

        client := &http.Client{}
        request, err := http.NewRequest("POST", host+"/api/admin/users", bytes.NewBuffer([]byte(createUserPayload)))
        }
}
Code Block
titleGo
collapsetrue
package main

import (
	""bytes""
	""encoding/json""
	""fmt""
	""io/ioutil""
	""math/rand""
	""net/http""
	""time""
)

func main() {
	host := ""http://localhost:8080/Yellowfin""
	restUsername := ""admin@yellowfin.com.au""
	restPassword := ""test""
	userToRetrieve := ""admin@yellowfin.com.au""

	token, err := generateToken(host, restUsername, restPassword)
	if err != nil {
Code Block
languagejs
titleJavaScript
collapsetrue
const fetch = require("node-fetch");

async function main() {
    const host = "http://localhost:8080/Yellowfin";
    const restUsername = "admin@yellowfin.com.au";
    const restPassword = "test";

    const createUserPayload = JSON.stringify([{
        userId: "user1",
        emailAddress: "user1@yellowfin.com.au",
        roleCode: "Consumer & Collaborator",
        password: "test",
        firstName: "User",
        lastName: "One",
        languageCode: "EN",
        timeZoneCode: "AUSTRALIA/SYDNEY"
    }]);

    const token = await generateToken(host, restUsername, restPassword);

    if (token === null) {
        console.error("Failed to retrieve access token");
        return;
    }

    console.log("Payload:", createUserPayload);

    const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);

    const headers = {
        'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}, token=${token}`,
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    };

    try {
        const response = await fetch(`${host}/api/admin/users`, {
Code Block
languagephp
titlePHP
collapsetrue
<?php
function main() {
    $host = "http://localhost:8080/Yellowfin";
    $restUsername = "admin@yellowfin.com.au";
    $restPassword = "test";

    $createUserPayload = json_encode(array(
        array(
            "userId" => "user1",
            "emailAddress" => "user1@yellowfin.com.au",
            "roleCode" => "Consumer & Collaborator",
            "password" => "test",
            "firstName" => "User",
            "lastName" => "One",
            "languageCode" => "EN",
            "timeZoneCode" => "AUSTRALIA/SYDNEY"
        )
    ));

    try {
        $token = generateToken($host, $restUsername, $restPassword);
    } catch (Exception $e) {
        echo "Error generating token: " . $e->getMessage();
        return;
    }

    echo "Payload: " . $createUserPayload . "\n";

    $nonce = mt_rand();
    $headers = array(
        'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce . ', token=' . $token,
        'Accept: application/vnd.yellowfin.api-v1+json',
        'Content-Type: application/json'
    );

    try {
        $response = httpRequest('POST', "$host/api/admin/users", $headers, $createUserPayload);
        echo $response;
    } catch (Exception $e) {

		fmt.Println(""Error generating token:"", err)
		return
	}

	fmt.Println(""Retrieving User:"", userToRetrieve)

	client := &http.Client{}
	req, err := http.NewRequest(""GET"", host+""/api/rpc/users/user-details-by-username/""+userToRetrieve, nil)
	if err != nil {
		fmt.Println(""Error creating request:"", err)
		return
	}

	nonce := rand.Int63()

	req.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d, token=%s"", time.Now().UnixMilli(), nonce, token))
	req.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
	req.Header.Set(""Content-Type"", ""application/json"")

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println(""Error sending request:"", err)
		return
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println(""Error reading response body:"", err)
		return
	}

	fmt.Println(string(body))
}

func generateToken(host, restUsername, restPassword string) (string, error) {
	// Generate nonce
	nonce := rand.Int63()

	// Create request body
	requestBody, err := json.Marshal(map[string]string{
		""userName"": restUsername,
		""password"": restPassword,
	})
	if err != nil {
		fmt.Println(""Error marshaling request body:"", err)
		return """", err
	}

	// Create HTTP client
	client := &http.Client{}

	// Create HTTP request
	request, err := http.NewRequest(""POST"", host+""/api/refresh-tokens"", bytes.NewBuffer(requestBody))
	if err != nil {
		fmt.Println(""Error creating request:"", err)
		return """", err
	}

	// Add request headers
	request.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d"", time.Now().UnixMilli(), nonce))
	request.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
	request.Header.Set(""Content-Type"", ""application/json"")

	// Send HTTP request
	response, err := client.Do(request)
	if err != nil {
		fmt.Println(""Error sending request:"", err)
		return """", err
	}
	defer response.Body.Close()

	// Read response body
	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println(""Error reading response body:"", err)
		return """", err
	}

	// Parse JSON response
	var jsonResponse map[string]interface{}
	err = json.Unmarshal(responseBody, &jsonResponse)
	if err != nil {
		fmt.Println(""Error parsing JSON response:"", err)
		return """", err
	}

	// Get access token from response
	accessToken, ok := jsonResponse[""_embedded""].(map[string]interface{})[""accessToken""].(map[string]interface{})[""securityToken""].(string)
	if !ok {
		fmt.Println(""Token not retrieved"")
		return """", fmt.Errorf(""Token not retrieved successfully"")
	}

	return accessToken, nil
}
Code Block
languagejs
titleJavaScript
collapsetrue
const fetch = require('node-fetch');

async function main() {
    const host = ""http://localhost:8080/Yellowfin"";
    const restUsername = ""admin@yellowfin.com.au"";
    const restPassword = ""test"";
    const userToRetrieve = ""admin@yellowfin.com.au"";

    try {
        const token = await generateToken(host, restUsername, restPassword);
        console.log(""Retrieving User:"", userToRetrieve);

        const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);

        const headers = {
            'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}, token=${token}`,
            'Accept': 'application/vnd.yellowfin.api-v1+json',
            'Content-Type': 'application/json'
        };

        const response = await fetch(`${host}/api/rpc/users/user-details-by-username/${userToRetrieve}`, {
            method: 'GET',
            headers: headers
        });

        const userResponse = await response.json();

        console.log(JSON.stringify(userResponse));
    } catch (error) {
        console.error(""Error:"", error.response ? error.response.data : error.message);
    }
}

async function generateToken(host, restUsername, restPassword) {
    // Generate nonce
    const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);

    // Create request headers
    const
Code Block
languagepy
titlePython
collapsetrue
import json
import random
import time

import requests

def main():
    host = "http://localhost:8080/Yellowfin"
    rest_username = "admin@yellowfin.com.au"
    rest_password = "test"

    create_user_payload = json.dumps([{
        "userId": "user1",
        "emailAddress": "user1@yellowfin.com.au",
        "roleCode": "Consumer & Collaborator",
        "password": "test",
        "firstName": "User",
        "lastName": "One",
        "languageCode": "EN",
        "timeZoneCode": "AUSTRALIA/SYDNEY"
    }])

    try:
        token = generate_token(host, rest_username, rest_password)
    except Exception as e:
        print(f"Error generating token: {e}")
        return

    print("Payload:", create_user_payload)

    nonce = random.randint(0, 2 ** 63 - 1)

    headers = {
        'Authorization': f'YELLOWFIN`YELLOWFIN ts=${int(timeDate.timenow() * 1000)}, nonce=${nonce}, token={token}'`,
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    };

     try:

Java | C# | Go | JavaScript | PHP | Python

Updating a User

Updating a user uses the same JSON model specified above. A model including the required changes can be consumed by PATCH /api/admin/users/{userId} (https://developers.yellowfinbi.com/dev/api-docs/current/#operation/updateUser ), where the {userId} is the integer identifier, as returned by GET /api/rpc/users/user-details-by-username/{user-name}

The update end-point supports only a single User JSON model, compared to the create user end-point which can accept an array of User JSON models.

The following examples update an existing user in various programming languages:

Java | C# | Go | JavaScript | PHP | Python

// Create request body
    const body = JSON.stringify({
        userName: restUsername,
        password: restPassword
    });

    try {
        // Make POST request
        const response = await fetch(`${host}/api/refresh-tokens`, {
            method: 'POST',
            headers: headers,
            body: body
        });

        // Check if request was successful
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        // Parse JSON response
        const jsonResponse = await response.json();
        const accessToken = jsonResponse._embedded.accessToken.securityToken;

        if (accessToken) {
            console.log(`Access Token: ${accessToken}`);
        } else {
            console.log(""Token not retrieved"");
        }

        return accessToken;
    } catch (error) {
        console.error(""Error:"", error.message);
    }

    return null;
}

main();
Code Block
languagephp
titlePHP
collapsetrue
<?php
function main() {
    $host = ""http://localhost:8080/Yellowfin"";
    $restUsername = ""admin@yellowfin.com.au"";
    $restPassword = ""test"";
    $userToRetrieve = ""admin@yellowfin.com.au"";

    try {
        $token = generateToken($host, $restUsername, $restPassword);
        echo ""Retrieving User: $userToRetrieve\n"";

        $nonce = mt_rand();

        $headers = [
            'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce . ', token=' . $token,
            'Accept: application/vnd.yellowfin.api-v1+json',
            'Content-Type: application/json'
        ];

        $url = ""$host/api/rpc/users/user-details-by-username/$userToRetrieve"";
        $response = httpRequest('GET', $url, $headers);

        echo $response . ""\n"";
    } catch (Exception $e) {
        echo ""Error: "" . $e->getMessage() . ""\n"";
    }
}

function generateToken($host, $restUsername, $restPassword) {
    // Generate nonce
    $nonce = mt_rand();

    // Create request body
    $requestBody = json_encode(array(
        ""userName"" => $restUsername,
        ""password"" => $restPassword
    ));

    // Create request headers
    $headers = array(
        'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce,
        'Accept: application/vnd.yellowfin.api-v1+json',
        'Content-Type: application/json'
    );

    $response = httpRequest('POST', ""$host/api/refresh-tokens"", $headers, $requestBody);

    // Parse JSON response
    $jsonResponse = json_decode($response, true);

    // Get access token from response
    if (isset($jsonResponse[""_embedded""][""accessToken""][""securityToken""])) {
        $accessToken = $jsonResponse[""_embedded""][""accessToken""][""securityToken""];
        echo ""Access Token: "" . $accessToken;

        return $accessToken;
    } else {
        throw new Exception(""Token not retrieved successfully"");
    }
}

function httpRequest($method, $url, $headers, $data = null) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    if ($data !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        throw new Exception('Error: ' . curl_error($ch));
    }

    curl_close($ch);

    return $response;
}

main()
?>
Code Block
languagepy
titlePython
collapsetrue
import json
import random
import time

import requests

def main():
    host = ""http://localhost:8080/yellowfinHead""
    rest_username = ""admin@yellowfin.com.au""
    rest_password = ""test""
    user_to_retrieve = ""admin@yellowfin.com.au""

    try:
        token = generate_token(host, rest_username, rest_password)
        print(""Retrieving User:"", user_to_retrieve)

        nonce = str(random.randint(1, 1000000000))

        headers = {
            'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}, token={token}',
            'Accept': 'application/vnd.yellowfin.api-v1+json',
            'Content-Type': 'application/json'
        }

        url = f""{host}/api/rpc/users/user-details-by-username/{user_to_retrieve}""
        response = requests.get(url, headers=headers)

        if response.status_code == 200:
            print(response.text)
        else:
            print(""Failed to retrieve user details. Status code:"", response.status_code)
    except Exception as e:
        print(""Error:"", e)

def generate_token(host, rest_username, rest_password):
    nonce = random.randint(0, 2 ** 63 - 1)

    # Create request body
    request_body = json.dumps({
        ""userName"": rest_username,
        ""password"": rest_password
    })

    # Create request headers
    headers = {
        'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}',
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    }

    # Send HTTP request
    response = requests.post(host + ""/api/refresh-tokens"", headers=headers, data=request_body)

    # Check response status
    if response.status_code == 200:
        # Parse JSON response
        json_response = response.json()
        access_token = json_response[""_embedded""][""accessToken""][""securityToken""]
        print(""Access Token:"", access_token)

        return access_token
    else:
        raise Exception(""Token not retrieved successfully"")

if __name__ == ""__main__"":
    main()

Creating a User

Create a new user by providing an array of user models to POST /api/admin/users createUserAdmin . Pass multiple user models to create multiple users simultaneously.

The following examples create a new user in various programming languages.

This Java Code example uses Apache HTTP Client and GSON for handling REST calls and JSON serialization.
Code Block
languagejava
titleJava
collapsetrue
package rest.code.examples;


import java.io.IOException;
import java.util.Random;
import org.apache.hc.client5.http.fluent.Content;
import org.apache.hc.client5.http.fluent.Request;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
 * Create a user using the Yellowfin REST API
 */
public class CreateAUser {
    public static void main(String[] args) throws Exception {

        String host = ""http://localhost:8080/Yellowfin"";
        String restUsername = ""admin@yellowfin.com.au"";
        String restPassword = ""test"";

        String createUserPayload = ""[ {"" +
                ""  \""userId\"": \""user1\"","" +
                ""  \""emailAddress\"": \""user1@yellowfin.com.au\"","" +
                ""  \""roleCode\"": \""Consumer & Collaborator\"","" +
                ""  \""password\"": \""test\"","" +
                ""  \""firstName\"": \""User\"","" +
                ""  \""lastName\"": \""One\"","" +
                ""  \""languageCode\"": \""EN\"","" +
                ""  \""timeZoneCode\"": \""AUSTRALIA/SYDNEY\"""" +
                "" } ]"";




        String token = generateToken(host, restUsername, restPassword);

        System.out.println(""Payload: "" + createUserPayload);

        Content c = Request.post(host + ""/api/admin/users"")
                .addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong() + "", token="" + token)
                .addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
                .addHeader(""Content-Type"", ""application/json"")
                .bodyString(createUserPayload, null)
                .execute().returnContent();

        System.out.print(c.asString());

    }

    public static String generateToken(String host, String username, String password) throws IOException {

        Content c = Request.post(host + ""/api/refresh-tokens"")
                .addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong())
                .addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
                .addHeader(""Content-Type"", ""application/json"")
                .bodyString(""{ \""userName\"": \""""+ username + ""\"",\""password\"": \""""+ password + ""\""}"", null)
                .execute().returnContent();

        JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
        JsonElement accessToken = jsonObject.getAsJsonObject(""_embedded"").getAsJsonObject(""accessToken"").get(""securityToken"");

        if (accessToken!=null) {
            System.out.println(""Access Token: "" + accessToken);
        } else {
            System.out.println(""Token not retrieved successfully"");
            System.exit(-1);
        }
        return accessToken.getAsString();

    }

}
Code Block
languagec#
titleC#
collapsetrue
namespace YellowfinAPIExamples;

using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class CreateAUser
{
    static async Task Main(string[] args)
    {
        string host = ""http://localhost:8080/Yellowfin"";
        string restUsername = ""admin@yellowfin.com.au"";
        string restPassword = ""test"";
            
        string createUserPayload = ""[ {"" +
                                   ""  \""userId\"": \""user1\"","" +
                                   ""  \""emailAddress\"": \""user1@yellowfin.com.au\"","" +
                                   ""  \""roleCode\"": \""Consumer & Collaborator\"","" +
                                   ""  \""password\"": \""test\"","" +
                                   ""  \""firstName\"": \""User\"","" +
                                   ""  \""lastName\"": \""One\"","" +
                                   ""  \""languageCode\"": \""EN\"","" +
                                   ""  \""timeZoneCode\"": \""AUSTRALIA/SYDNEY\"""" +
                                   "" } ]"";

        string token = await GenerateToken(host, restUsername, restPassword);

        Console.WriteLine(""Payload: "" + createUserPayload);

        using (HttpClient client = new HttpClient())
        {
            long nonce = new Random().NextInt64();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, host + ""/api/admin/users"");
            request.Headers.Add(""Authorization"", ""YELLOWFIN ts="" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + "", nonce="" + nonce + "", token="" + token);
            request.Headers.Add(""Accept"", ""application/vnd.yellowfin.api-v1+json"");
            request.Content = new StringContent(createUserPayload, System.Text.Encoding.UTF8, ""application/json"");

            HttpResponseMessage response = await client.SendAsync(request);
            string content = await response.Content.ReadAsStringAsync();

            Console.WriteLine(content);
        }
    }
    
    static async Task<string> GenerateToken(string host, string restUsername, string restPassword)
    {
        using (var client = new HttpClient())
        {
            // Generate nonce
            long nonce = new Random().NextInt64();
            
            // Create HTTP request
            var request = new HttpRequestMessage(HttpMethod.Post, host + ""/api/refresh-tokens"");
            request.Headers.Add(""Authorization"", ""YELLOWFIN ts="" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + "", nonce="" + nonce);
            request.Headers.Add(""Accept"", ""application/vnd.yellowfin.api-v1+json"");
            request.Content = new StringContent(
                JsonConvert.SerializeObject(new { userName = restUsername, password = restPassword }),
                MediaTypeHeaderValue.Parse(""application/json"")
            );

            // Send request and get response
            HttpResponseMessage response = await client.SendAsync(request);
            string responseContent = await response.Content.ReadAsStringAsync();

            // Parse JSON response
            JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseContent);
            string accessToken = jsonObject[""_embedded""][""accessToken""][""securityToken""].ToString();

            if (!string.IsNullOrEmpty(accessToken))
            {
                Console.WriteLine(""Access Token: "" + accessToken);
            }
            else
            {
                Console.WriteLine(""Token not retrieved"");
                Environment.Exit(-1);
            }

            return accessToken;
        }
    }
}
Code Block
titleGo
collapsetrue
package main

import (
        ""bytes""
        ""encoding/json""
        ""fmt""
        ""io/ioutil""
        ""math/rand""
        ""net/http""
        ""time""
)

func main() {
        host := ""http://localhost:8080/Yellowfin""
        restUsername := ""admin@yellowfin.com.au""
        restPassword := ""test""

        createUserPayload := `[{
                ""userId"": ""user1"",
                ""emailAddress"": ""user1@yellowfin.com.au"",
                ""roleCode"": ""Consumer & Collaborator"",
                ""password"": ""test"",
                ""firstName"": ""User"",
                ""lastName"": ""One"",
                ""languageCode"": ""EN"",
                ""timeZoneCode"": ""AUSTRALIA/SYDNEY""
        }]`

        token, err := generateToken(host, restUsername, restPassword)
        if err != nil {
                fmt.Println(""Error generating token:"", err)
                return
        }

        fmt.Println(""Payload:"", createUserPayload)

        client := &http.Client{}
        request, err := http.NewRequest(""POST"", host+""/api/admin/users"", bytes.NewBuffer([]byte(createUserPayload)))
        if err != nil {
                fmt.Println(""Error creating request:"", err)
                return
        }

        request.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d, token=%s"", time.Now().UnixMilli(), rand.Int63(), token))
        request.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
        request.Header.Set(""Content-Type"", ""application/json"")

        response, err := client.Do(request)
        if err != nil {
                fmt.Println(""Error sending request:"", err)
                return
        }
        defer response.Body.Close()

        body, err := ioutil.ReadAll(response.Body)
        if err != nil {
                fmt.Println(""Error reading response body:"", err)
                return
        }

        fmt.Println(string(body))
}

func generateToken(host, restUsername, restPassword string) (string, error) {
        // Generate nonce
        nonce := rand.Int63()

        // Create request body
        requestBody, err := json.Marshal(map[string]string{
                ""userName"": restUsername,
                ""password"": restPassword,
        })
        if err != nil {
                fmt.Println(""Error marshaling request body:"", err)
                return """", err
        }

        // Create HTTP client
        client := &http.Client{}

        // Create HTTP request
        request, err := http.NewRequest(""POST"", host+""/api/refresh-tokens"", bytes.NewBuffer(requestBody))
        if err != nil {
                fmt.Println(""Error creating request:"", err)
                return """", err
        }

        // Add request headers
        request.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d"", time.Now().UnixMilli(), nonce))
        request.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
        request.Header.Set(""Content-Type"", ""application/json"")

        // Send HTTP request
        response, err := client.Do(request)
        if err != nil {
                fmt.Println(""Error sending request:"", err)
                return """", err
        }
        defer response.Body.Close()

        // Read response body
        responseBody, err := ioutil.ReadAll(response.Body)
        if err != nil {
                fmt.Println(""Error reading response body:"", err)
                return """", err
        }

        // Parse JSON response
        var jsonResponse map[string]interface{}
        err = json.Unmarshal(responseBody, &jsonResponse)
        if err != nil {
                fmt.Println(""Error parsing JSON response:"", err)
                return """", err
        }

        // Get access token from response
        accessToken, ok := jsonResponse[""_embedded""].(map[string]interface{})[""accessToken""].(map[string]interface{})[""securityToken""].(string)
        if !ok {
                fmt.Println(""Token not retrieved"")
                return """", fmt.Errorf(""Token not retrieved successfully"")
        }

        return accessToken, nil
}
Code Block
languagejs
titleJavaScript
collapsetrue
const fetch = require(""node-fetch"");

async function main() {
    const host = ""http://localhost:8080/Yellowfin"";
    const restUsername = ""admin@yellowfin.com.au"";
    const restPassword = ""test"";

    const createUserPayload = JSON.stringify([{
        userId: ""user1"",
        emailAddress: ""user1@yellowfin.com.au"",
        roleCode: ""Consumer & Collaborator"",
        password: ""test"",
        firstName: ""User"",
        lastName: ""One"",
        languageCode: ""EN"",
        timeZoneCode: ""AUSTRALIA/SYDNEY""
    }]);

    const token = await generateToken(host, restUsername, restPassword);

    if (token === null) {
        console.error(""Failed to retrieve access token"");
        return;
    }

    console.log(""Payload:"", createUserPayload);

    const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);

    const headers = {
        'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}, token=${token}`,
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    };

    try {
        const response = await fetch(`${host}/api/admin/users`, {
            method: 'POST',
            headers: headers,
            body: createUserPayload
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const responseBody = await response.text();
        console.log(responseBody);
    } catch (error) {
        console.error(""Error:"", error.message);
    }
}

async function generateToken(host, restUsername, restPassword) {
    // Generate nonce
    const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);

    // Create request headers
    const headers = {
        'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}`,
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    };

    // Create request body
    const body = JSON.stringify({
        userName: restUsername,
        password: restPassword
    });

    try {
        // Make POST request
        const response = await fetch(`${host}/api/refresh-tokens`, {
            method: 'POST',
            headers: headers,
            body: body
        });

        // Check if request was successful
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        // Parse JSON response
        const jsonResponse = await response.json();
        const accessToken = jsonResponse._embedded.accessToken.securityToken;

        if (accessToken) {
            console.log(`Access Token: ${accessToken}`);
        } else {
            console.log(""Token not retrieved"");
        }

        return accessToken;
    } catch (error) {
        console.error(""Error:"", error.message);
    }

    return null;
}

main();
Code Block
languagephp
titlePHP
collapsetrue
<?php
function main() {
    $host = ""http://localhost:8080/Yellowfin"";
    $restUsername = ""admin@yellowfin.com.au"";
    $restPassword = ""test"";

    $createUserPayload = json_encode(array(
        array(
            ""userId"" => ""user1"",
            ""emailAddress"" => ""user1@yellowfin.com.au"",
            ""roleCode"" => ""Consumer & Collaborator"",
            ""password"" => ""test"",
            ""firstName"" => ""User"",
            ""lastName"" => ""One"",
            ""languageCode"" => ""EN"",
            ""timeZoneCode"" => ""AUSTRALIA/SYDNEY""
        )
    ));

    try {
        $token = generateToken($host, $restUsername, $restPassword);
    } catch (Exception $e) {
        echo ""Error generating token: "" . $e->getMessage();
        return;
    }

    echo ""Payload: "" . $createUserPayload . ""\n"";

    $nonce = mt_rand();
    $headers = array(
        'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce . ', token=' . $token,
        'Accept: application/vnd.yellowfin.api-v1+json',
        'Content-Type: application/json'
    );

    try {
        $response = httpRequest('POST', ""$host/api/admin/users"", $headers, $createUserPayload);
        echo $response;
    } catch (Exception $e) {
        echo ""Error sending request: "" . $e->getMessage();
    }
}

function generateToken($host, $restUsername, $restPassword) {
    // Generate nonce
    $nonce = mt_rand();

    // Create request body
    $requestBody = json_encode(array(
        ""userName"" => $restUsername,
        ""password"" => $restPassword
    ));

    // Create request headers
    $headers = array(
        'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce,
        'Accept: application/vnd.yellowfin.api-v1+json',
        'Content-Type: application/json'
    );

    $response = httpRequest('POST', ""$host/api/refresh-tokens"", $headers, $requestBody);

    // Parse JSON response
    $jsonResponse = json_decode($response, true);

    // Get access token from response
    if (isset($jsonResponse[""_embedded""][""accessToken""][""securityToken""])) {
        $accessToken = $jsonResponse[""_embedded""][""accessToken""][""securityToken""];
        echo ""Access Token: "" . $accessToken;

        return $accessToken;
    } else {
        throw new Exception(""Token not retrieved successfully"");
    }
}

function httpRequest($method, $url, $headers, $data = null) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    if ($data !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        throw new Exception('Error: ' . curl_error($ch));
    }

    curl_close($ch);

    return $response;
}

main()
?>
Code Block
languagepy
titlePython
collapsetrue
import json
import random
import time

import requests

def main():
    host = ""http://localhost:8080/Yellowfin""
    rest_username = ""admin@yellowfin.com.au""
    rest_password = ""test""

    create_user_payload = json.dumps([{
        ""userId"": ""user1"",
        ""emailAddress"": ""user1@yellowfin.com.au"",
        ""roleCode"": ""Consumer & Collaborator"",
        ""password"": ""test"",
        ""firstName"": ""User"",
        ""lastName"": ""One"",
        ""languageCode"": ""EN"",
        ""timeZoneCode"": ""AUSTRALIA/SYDNEY""
    }])

    try:
        token = generate_token(host, rest_username, rest_password)
    except Exception as e:
        print(f""Error generating token: {e}"")
        return

    print(""Payload:"", create_user_payload)

    nonce = random.randint(0, 2 ** 63 - 1)

    headers = {
        'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}, token={token}',
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    }

    try:
        response = requests.post(host + ""/api/admin/users"", headers=headers, data=create_user_payload)
        response.raise_for_status()
        print(response.text)
    except requests.RequestException as e:
        print(f""Error sending request: {e}"")


def generate_token(host, rest_username, rest_password):
    nonce = random.randint(0, 2 ** 63 - 1)

    # Create request body
    request_body = json.dumps({
        ""userName"": rest_username,
        ""password"": rest_password
    })

    # Create request headers
    headers = {
        'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={nonce}',
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    }

    # Send HTTP request
    response = requests.post(host + ""/api/refresh-tokens"", headers=headers, data=request_body)

    # Check response status
    if response.status_code == 200:
        # Parse JSON response
        json_response = response.json()
        access_token = json_response[""_embedded""][""accessToken""][""securityToken""]
        print(""Access Token:"", access_token)

        return access_token
    else:
        raise Exception(""Token not retrieved successfully"")

if __name__ == ""__main__"":
    main()

Updating a User

Updating a user uses the same JSON model specified above. A model including the required changes can be consumed by PATCH /api/admin/users/{userId} Update a User, where the {userId} is the integer identifier, as returned by GET /api/rpc/users/user-details-by-username/{user-name}

The update end-point supports only a single User JSON model, compared to the create user end-point which can accept an array of User JSON models.

The following examples update an existing user in various programming languages:

This Java Code example uses Apache HTTP Client and GSON for handling REST calls and JSON serialization.
Code Block
languagejava
titleJava
collapsetrue
package rest.code.examples;
import java.io.IOException;
import java.util.Random;
import org.apache.hc.client5.http.fluent.Content;
import org.apache.hc.client5.http.fluent.Request;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
 * Create a user using the Yellowfin REST API
 */
public class UpdateAUser {
    public static void main(String[] args) throws Exception {

        String host = ""http://localhost:8080/yellowfinHead"";
        String restUsername = ""admin@yellowfin.com.au"";
        String restPassword = ""test"";

        Integer userIp = 13235;

        String updateUserPayload =
                ""{"" +
                        ""  \""emailAddress\"": \""user1@yellowfin.com.au\"","" +
                        ""  \""roleCode\"": \""Consumer & Collaborator\"","" +
                        ""  \""password\"": \""test\"","" +
                        ""  \""firstName\"": \""User\"","" +
                        ""  \""lastName\"": \""Two\"","" +
                        ""  \""languageCode\"": \""EN\"","" +
                        ""  \""timeZoneCode\"": \""AUSTRALIA/SYDNEY\"""" +
                        ""}"";

        String token = generateToken(host, restUsername, restPassword);

        System.out.println(""Payload: "" + updateUserPayload);

        Content c = Request.patch(host + ""/api/admin/users/"" + userIp)
                .addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong() + "", token="" + token)
                .addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
                .addHeader(""Content-Type"", ""application/json"")
                .bodyString(updateUserPayload, null)
                .execute().returnContent();

        System.out.print(c.asString());

    }

    public static String generateToken(String host, String username, String password) throws IOException {

        Content c = Request.post(host + ""/api/refresh-tokens"")
                .addHeader(""Authorization"", ""YELLOWFIN ts="" + System.currentTimeMillis() + "" , nonce="" + new Random().nextLong())
                .addHeader(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
                .addHeader(""Content-Type"", ""application/json"")
                .bodyString(""{ \""userName\"": \""""+ username + ""\"",\""password\"": \""""+ password + ""\""}"", null)
                .execute().returnContent();

        JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
        JsonElement accessToken = jsonObject.getAsJsonObject(""_embedded"").getAsJsonObject(""accessToken"").get(""securityToken"");

        if (accessToken!=null) {
            System.out.println(""Access Token: "" + accessToken);
        } else {
            System.out.println(""Token not retrieved successfully"");
            System.exit(-1);
        }
        return accessToken.getAsString();

    }

}
Code Block
languagec#
titleC#
collapsetrue
namespace YellowfinAPIExamples
{
    using System;
    using System.Net.Http;
    using System.Net.Http.Headers;
    using System.Threading.Tasks;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;

    class UpdateAUser
    {
        static async Task Main(string[] args)
        {
            string host = ""http://localhost:8080/yellowfinHead"";
            string restUsername = ""admin@yellowfin.com.au"";
            string restPassword = ""test"";

            int userIp = 13235;

            string updateUserPayload = JsonConvert.SerializeObject(new
            {
                emailAddress = ""user1@yellowfin.com.au"",
                roleCode = ""Consumer & Collaborator"",
                password = ""test"",
                firstName = ""User"",
                lastName = ""Two"",
                languageCode = ""EN"",
                timeZoneCode = ""AUSTRALIA/SYDNEY""
            });

            string token = await GenerateToken(host, restUsername, restPassword);

            using (var client = new HttpClient())
            {
                // Generate nonce
                long nonce = new Random().NextInt64();

                // Create HTTP request
                var request = new HttpRequestMessage(HttpMethod.Patch, $""{host}/api/admin/users/{userIp}"");
                request.Headers.Add(""Authorization"", $""YELLOWFIN ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()} , nonce={nonce}, token={token}"");
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));
                request.Content = new StringContent(updateUserPayload, System.Text.Encoding.UTF8, ""application/json"");

                // Send request and get response
                HttpResponseMessage response = await client.SendAsync(request);
                string responseContent = await response.Content.ReadAsStringAsync();

                Console.WriteLine(responseContent);
            }
        }

        public static async Task<string> GenerateToken(string host, string username, string password)
        {
            using (var client = new HttpClient())
            {
                // Generate nonce
                long nonce = new Random().NextInt64();

                // Create HTTP request
                var request = new HttpRequestMessage(HttpMethod.Post, $""{host}/api/refresh-tokens"");
                request.Headers.Add(""Authorization"", $""YELLOWFIN ts={DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()} , nonce={nonce}"");
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));
                request.Content = new StringContent(
                    JsonConvert.SerializeObject(new { userName = username, password = password }),
                    System.Text.Encoding.UTF8,
                    ""application/json""
                );

                // Send request and get response
                HttpResponseMessage response = await client.SendAsync(request);
                string responseContent = await response.Content.ReadAsStringAsync();

                // Parse JSON response
                JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseContent);
                string accessToken = jsonObject[""_embedded""][""accessToken""][""securityToken""].ToString();

                if (!string.IsNullOrEmpty(accessToken))
                {
                    Console.WriteLine(""Access Token: "" + accessToken);
                }
                else
                {
                    Console.WriteLine(""Token not retrieved successfully"");
                    Environment.Exit(-1);
                }
                return accessToken;
            }
        }
    }
}
Code Block
titleGo
collapsetrue
package main

import (
	""bytes""
	""encoding/json""
	""fmt""
	""io/ioutil""
	""math/rand""
	""net/http""
	""time""
)

func main() {
	host := ""http://localhost:8080/yellowfinHead""
	restUsername := ""admin@yellowfin.com.au""
	restPassword := ""test""
	userIp := 13235

	updateUserPayload := map[string]string{
		""emailAddress"": ""user1@yellowfin.com.au"",
		""roleCode"":     ""Consumer & Collaborator"",
		""password"":     ""test"",
		""firstName"":    ""User"",
		""lastName"":     ""Two"",
		""languageCode"": ""EN"",
		""timeZoneCode"": ""AUSTRALIA/SYDNEY"",
	}

	token, err := generateToken(host, restUsername, restPassword)
	if err != nil {
		fmt.Println(""Error generating token:"", err)
		return
	}

	payloadBytes, err := json.Marshal(updateUserPayload)
	if err != nil {
		fmt.Println(""Error marshaling payload:"", err)
		return
	}

	nonce := rand.Int63()

	client := &http.Client{}
	request, err := http.NewRequest(""PATCH"", fmt.Sprintf(""%s/api/admin/users/%d"", host, userIp), bytes.NewBuffer(payloadBytes))
	if err != nil {
		fmt.Println(""Error creating request:"", err)
		return
	}

	request.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d, token=%s"", time.Now().UnixMilli(), nonce, token))
	request.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
	request.Header.Set(""Content-Type"", ""application/json"")

	response, err := client.Do(request)
	if err != nil {
		fmt.Println(""Error sending request:"", err)
		return
	}
	defer response.Body.Close()

	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Println(""Error reading response body:"", err)
		return
	}

	fmt.Print(string(responseBody))
}

func generateToken(host, username, password string) (string, error) {
	requestBody, err := json.Marshal(map[string]string{
		""userName"": username,
		""password"": password,
	})
	if err != nil {
		return """", fmt.Errorf(""error marshaling request body: %v"", err)
	}

	nonce := rand.Int63()

	client := &http.Client{}
	request, err := http.NewRequest(""POST"", fmt.Sprintf(""%s/api/refresh-tokens"", host), bytes.NewBuffer(requestBody))
	if err != nil {
		return """", fmt.Errorf(""error creating request: %v"", err)
	}

	request.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d"", time.Now().UnixMilli(), nonce))
	request.Header.Set(""Accept"", ""application/vnd.yellowfin.api-v1+json"")
	request.Header.Set(""Content-Type"", ""application/json"")

	response, err := client.Do(request)
	if err != nil {
		return """", fmt.Errorf(""error sending request: %v"", err)
	}
	defer response.Body.Close()

	responseBody, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return """", fmt.Errorf(""error reading response body: %v"", err)
	}

	var jsonResponse map[string]interface{}
	err = json.Unmarshal(responseBody, &jsonResponse)
	if err != nil {
		return """", fmt.Errorf(""error parsing JSON response: %v"", err)
	}

	accessToken, ok := jsonResponse[""_embedded""].(map[string]interface{})[""accessToken""].(map[string]interface{})[""securityToken""].(string)
	if !ok {
		return """", fmt.Errorf(""token not retrieved"")
	}

	fmt.Println(""Access Token:"", accessToken)
	return accessToken, nil
}
Code Block
languagejs
titleJavaScript
collapsetrue
const fetch = require('node-fetch');

async function main() {
    const host = ""http://localhost:8080/yellowfinHead"";
    const restUsername = ""admin@yellowfin.com.au"";
    const restPassword = ""test"";
    const userIp = 13235;

    const updateUserPayload = JSON.stringify({
        emailAddress: ""user1@yellowfin.com.au"",
        roleCode: ""Consumer & Collaborator"",
        password: ""test"",
        firstName: ""User"",
        lastName: ""Four"",
        languageCode: ""EN"",
        timeZoneCode: ""AUSTRALIA/SYDNEY""
    });

    const token = await generateToken(host, restUsername, restPassword);

    console.log(""Payload:"", updateUserPayload);

    const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
    const headers = {
        'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}, token=${token}`,
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    };

    try {
        const response = await fetch(`${host}/api/admin/users/${userIp}`, {
            method: 'PATCH',
            headers: headers,
            body: updateUserPayload
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const responseBody = await response.text();
        console.log(responseBody);
    } catch (error) {
        console.error(""Error:"", error.message);
    }
}

async function generateToken(host, username, password) {
    const nonce = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
    const headers = {
        'Authorization': `YELLOWFIN ts=${Date.now()}, nonce=${nonce}`,
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    };
    const body = JSON.stringify({
        userName: username,
        password: password
    });

    try {
        const response = await fetch(`${host}/api/refresh-tokens`, {
            method: 'POST',
            headers: headers,
            body: body
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const jsonResponse = await response.json();
        const accessToken = jsonResponse._embedded.accessToken.securityToken;

        if (accessToken) {
            console.log(`Access Token: ${accessToken}`);
            return accessToken;
        } else {
            console.log(""Token not retrieved successfully"");
            process.exit(-1);
        }
    } catch (error) {
        console.error(""Error:"", error.message);
        process.exit(-1);
    }
}

main();
Code Block
languagephp
titlePHP
collapsetrue
<?php

function main()
{
    $host = ""http://localhost:8080/yellowfinHead"";
    $restUsername = ""admin@yellowfin.com.au"";
    $restPassword = ""test"";
    $userIp = 13235;

    $updateUserPayload = json_encode(array(
        ""emailAddress"" => ""user1@yellowfin.com.au"",
        ""roleCode"" => ""Consumer & Collaborator"",
        ""password"" => ""test"",
        ""firstName"" => ""User"",
        ""lastName"" => ""Two"",
        ""languageCode"" => ""EN"",
        ""timeZoneCode"" => ""AUSTRALIA/SYDNEY""
    ));

    $token = generateToken($host, $restUsername, $restPassword);

    echo ""Payload: "" . $updateUserPayload . PHP_EOL;

    $nonce = mt_rand();
    $headers = array(
        'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce . ', token=' . $token,
        'Accept: application/vnd.yellowfin.api-v1+json',
        'Content-Type: application/json'
    );

    $response = httpRequest('PATCH', ""$host/api/admin/users/$userIp"", $headers, $updateUserPayload);

    echo $response . PHP_EOL;
}

function generateToken($host, $username, $password)
{
    $nonce = mt_rand();
    $headers = array(
        'Authorization: YELLOWFIN ts=' . intval(microtime(true) * 1000) . ', nonce=' . $nonce,
        'Accept: application/vnd.yellowfin.api-v1+json',
        'Content-Type: application/json'
    );

    $body = json_encode(array(
        ""userName"" => $username,
        ""password"" => $password
    ));

    $response = httpRequest('POST', ""$host/api/refresh-tokens"", $headers, $body);

    $jsonResponse = json_decode($response, true);

    if (isset($jsonResponse[""_embedded""][""accessToken""][""securityToken""])) {
        $accessToken = $jsonResponse[""_embedded""][""accessToken""][""securityToken""];
        echo ""Access Token: "" . $accessToken . PHP_EOL;
        return $accessToken;
    } else {
        echo ""Token not retrieved successfully"" . PHP_EOL;
        exit(-1);
    }
}

function httpRequest($method, $url, $headers, $data = null)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    if ($data !== null) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }

    $response = curl_exec($ch);

    if (curl_errno($ch)) {
        throw new Exception('Error: ' . curl_error($ch));
    }

    curl_close($ch);

    return $response;
}

main();
?>
Code Block
languagepy
titlePython
collapsetrue
import json
import random
import time
import requests

def main():
    host = ""http://localhost:8080/yellowfinHead""
    rest_username = ""admin@yellowfin.com.au""
    rest_password = ""test""
    user_ip = 13235

    update_user_payload = json.dumps({
        ""emailAddress"": ""user1@yellowfin.com.au"",
        ""roleCode"": ""Consumer & Collaborator"",
        ""password"": ""test"",
        ""firstName"": ""User"",
        ""lastName"": ""Seven"",
        ""languageCode"": ""EN"",
        ""timeZoneCode"": ""AUSTRALIA/SYDNEY""
    })

    token = generate_token(host, rest_username, rest_password)

    print(""Payload:"", update_user_payload)

    headers = {
        'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={random.randint(0, 2**63 - 1)}, token={token}',
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    }

    response = requests.patch(f""{host}/api/admin/users/{user_ip}"", headers=headers, data=update_user_payload)

    print(response.text)

def generate_token(host, username, password):
    headers = {
        'Authorization': f'YELLOWFIN ts={int(time.time() * 1000)}, nonce={random.randint(0, 2**63 - 1)}',
        'Accept': 'application/vnd.yellowfin.api-v1+json',
        'Content-Type': 'application/json'
    }

    body = json.dumps({
        ""userName"": username,
        ""password"": password
    })

    response = requests.post(f""{host}/api/refresh-tokens"", headers=headers, data=body)

    if response.status_code == 200:
        json_response = response.json()
        access_token = json_response[""_embedded""][""accessToken""][""securityToken""]
        print(""Access Token:"", access_token)
        return access_token
    else:
        print(""Token not retrieved successfully"")
        exit(-1)

if __name__ == ""__main__"":
    main()

Changing a user’s role 

A user’s role can be updated with the standard update end-point. This is done by setting the roleCode in the User JSON model when calling PATCH /api/admin/users/{userId} Update a User.

(https://developers.yellowfinbi.com/dev/api-docs/current/#operation/updateUser ) . The following example introduces the the GET /api/roles end-point to retrieve available roles. The example code will modify a user’s role to the first role returned by GET /api/roles.

...