Page History
...
A list of groups can be retrieved from the GET /api/user-groups end-point (https://developers.yellowfinbi.com/dev/api-docs/current/#tag/user-groups ) User Groups. This can also be used to check whether a group already exists, or to find a group by another identifier, like its name.
The following examples illustrate how to retrieve a list groups for a user in various programming languages.
Code Block | ||
---|---|---|
|
Java | C# | Go | JavaScript | PHP | Python
Creating a User Group
Groups can be created using the POST /api/user-groups end-point (https://developers.yellowfinbi.com/dev/api-docs/current/#operation/createUserGroup ). The model for User Group creation is:
{
"groupName": "New Group",
"groupDescription": "This a new group",
"groupStatus": "OPEN",
"isSecureGroup": "false"
}
After the successful creation of a group, the service will return a User Group model that contains the unique userGroupId of the new group. The userGroupId can then be used for identifying the group in other services. This service creates an empty group, group member components need to be added with the POST /api/user-groups/{groupId}/members end-point.
...
| ||||
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.JsonArray;
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 ListUserGroups {
public static void main(String[] args) throws Exception {
System.out.println(""List Groups"");
String host = ""http://localhost:8080/Yellowfin"";
String restUsername = ""admin@yellowfin.com.au"";
String restPassword = ""test"";
String token = generateToken(host, restUsername, restPassword);
Content c = Request.get(host + ""/api/user-groups"")
.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();
JsonObject jsonObject = new JsonParser().parse(c.asString()).getAsJsonObject();
JsonElement groupList = jsonObject.get(""items"");
JsonArray groups = groupList.getAsJsonArray();
System.out.println(groups.size() + "" groups retrieved."");
for (int i=0; i < groups.size(); i++ ) {
JsonObject group = groups.getAsJsonArray().get(i).getAsJsonObject();
System.out.println(""Group "" + group.get(""userGroupId"").getAsInt() + "": "" + group.get(""shortDescription"").getAsString());
}
}
/*
* This function generates an access token for a user that will grant them access to
* call REST API endpoints.
*/
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 | ||||||
---|---|---|---|---|---|---|
| ||||||
using System.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace YellowfinAPIExamples
{
public class ListUserGroups
{
static async Task Main(string[] args)
{
Console.WriteLine(""List Groups"");
string host = ""http://localhost:8080/Yellowfin"";
string restUsername = ""admin@yellowfin.com.au"";
string restPassword = ""test"";
string token = await GenerateToken(host, restUsername, restPassword);
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(""YELLOWFIN"", ""ts="" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + "" , nonce="" + new Random().NextInt64() + "", token="" + token);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));
HttpResponseMessage response = await httpClient.GetAsync(host + ""/api/user-groups"");
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseBody);
JArray groups = (JArray)jsonObject[""items""];
Console.WriteLine(groups.Count + "" groups retrieved."");
foreach (JObject group in groups)
{
Console.WriteLine(""Group "" + group[""userGroupId""] + "": "" + group[""shortDescription""]);
}
}
else
{
Console.WriteLine(""Failed to retrieve user groups. Status code: "" + response.StatusCode);
}
}
}
static async Task<string> GenerateToken(string host, string restUsername, string restPassword)
{
using (var httpClient = 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 }),
System.Text.Encoding.UTF8,
""application/json""
);
// Send request and get response
HttpResponseMessage response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
string responseContent = await response.Content.ReadAsStringAsync();
JObject jsonObject = JsonConvert.DeserializeObject<JObject>(responseContent);
string accessToken = jsonObject[""_embedded""][""accessToken""][""securityToken""].ToString();
if (!string.IsNullOrEmpty(accessToken))
{
Console.WriteLine(""Access Token: "" + accessToken);
return accessToken;
}
}
else
{
Console.WriteLine(""Token not retrieved successfully. Status code: "" + response.StatusCode);
}
Environment.Exit(-1);
return null; // Just to satisfy compiler, this won't be reached.
}
}
}
} |
Code Block | ||||
---|---|---|---|---|
| ||||
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""
token, err := generateToken(host, restUsername, restPassword)
if err != nil {
fmt.Println(""Error generating token:"", err)
return
}
fmt.Println(""List Groups"")
client := &http.Client{}
req, err := http.NewRequest(""GET"", host+""/api/user-groups"", 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
}
var jsonResponse map[string]interface{}
err = json.Unmarshal(body, &jsonResponse)
if err != nil {
fmt.Println(""Error parsing JSON response:"", err)
return
}
groupList := jsonResponse[""items""].([]interface{})
groups := make([]map[string]interface{}, len(groupList))
for i, v := range groupList {
groups[i] = v.(map[string]interface{})
}
fmt.Printf(""%d groups retrieved.\n"", len(groups))
for _, group := range groups {
fmt.Printf(""Group %v: %v\n"", group[""userGroupId""], group[""shortDescription""])
}
}
func generateToken(host, username, password string) (string, error) {
nonce := rand.Int63()
requestBody, err := json.Marshal(map[string]string{
""userName"": username,
""password"": password,
})
if err != nil {
return """", err
}
client := &http.Client{}
req, err := http.NewRequest(""POST"", host+""/api/refresh-tokens"", bytes.NewBuffer(requestBody))
if err != nil {
return """", err
}
req.Header.Set(""Authorization"", fmt.Sprintf(""YELLOWFIN ts=%d, nonce=%d"", time.Now().UnixMilli(), nonce))
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 {
return """", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return """", err
}
var jsonResponse map[string]interface{}
err = json.Unmarshal(body, &jsonResponse)
if err != nil {
return """", err
}
accessToken, ok := jsonResponse[""_embedded""].(map[string]interface{})[""accessToken""].(map[string]interface{})[""securityToken""].(string)
if !ok {
return """", fmt.Errorf(""Token not retrieved successfully"")
}
return accessToken, nil
} |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
const fetch = require(""node-fetch"");
async function main() {
console.log(""List Groups"");
const host = ""http://localhost:8080/Yellowfin"";
const restUsername = ""admin@yellowfin.com.au"";
const restPassword = ""test"";
const token = await generateToken(host, restUsername, restPassword);
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/user-groups`, {
headers: headers
});
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const responseBody = await response.json();
const groups = responseBody.items;
console.log(`${groups.length} groups retrieved.`);
groups.forEach(group => {
console.log(`Group ${group.userGroupId}: ${group.shortDescription}`);
});
} 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);
}
return null;
}
main(); |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
<?php
function main() {
echo ""List Groups\n"";
$host = ""http://localhost:8080/Yellowfin"";
$restUsername = ""admin@yellowfin.com.au"";
$restPassword = ""test"";
try {
$token = generateToken($host, $restUsername, $restPassword);
} catch (Exception $e) {
echo ""Error generating token: "" . $e->getMessage();
return;
}
$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('GET', ""$host/api/user-groups"", $headers);
$jsonResponse = json_decode($response, true);
$groups = $jsonResponse[""items""];
echo count($groups) . "" groups retrieved.\n"";
foreach ($groups as $group) {
echo ""Group "" . $group[""userGroupId""] . "": "" . $group[""shortDescription""] . ""\n"";
}
} catch (Exception $e) {
echo ""Error sending request: "" . $e->getMessage();
}
}
function generateToken($host, $restUsername, $restPassword) {
$nonce = mt_rand();
$requestBody = json_encode(array(
""userName"" => $restUsername,
""password"" => $restPassword
));
$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);
$jsonResponse = json_decode($response, true);
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 | ||||||
---|---|---|---|---|---|---|
| ||||||
import json
import random
import time
import requests
def main():
print(""List Groups"")
host = ""http://localhost:8080/Yellowfin""
rest_username = ""admin@yellowfin.com.au""
rest_password = ""test""
try:
token = generate_token(host, rest_username, rest_password)
# Create headers
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'
}
# Send request to get user groups
response = requests.get(host + ""/api/user-groups"", headers=headers)
response.raise_for_status()
# Parse response
groups = response.json()[""items""]
print(f""{len(groups)} groups retrieved."")
# Print group details
for group in groups:
print(f""Group {group['userGroupId']}: {group['shortDescription']}"")
except Exception as e:
print(f""Error: {e}"")
def generate_token(host, rest_username, rest_password):
# Generate nonce
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)
response.raise_for_status()
# Parse JSON response
json_response = response.json()
access_token = json_response[""_embedded""][""accessToken""][""securityToken""]
print(""Access Token:"", access_token)
return access_token
if __name__ == ""__main__"":
main() |
Creating a User Group
Groups can be created using the POST /api/user-groups end-point Create User Group. The model for User Group creation is:
Code Block |
---|
{
"groupName": "New Group",
"groupDescription": "This a new group",
"groupStatus": "OPEN",
"isSecureGroup": "false"
} |
After the successful creation of a group, the service will return a User Group model that contains the unique userGroupId of the new group. The userGroupId can then be used for identifying the group in other services. This service creates an empty group, group member components need to be added with the POST /api/user-groups/{groupId}/members end-point.
The following examples illustrate how to create a user group in various programming languages.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
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 CreateUserGroup {
public static void main(String[] args) throws Exception {
String host = ""http://localhost:8080/Yellowfin"";
String restUsername = ""admin@yellowfin.com.au"";
String restPassword = ""test"";
String newGroupName = ""New Group"";
String newGroupDescription = ""This is a new group"";
String token = generateToken(host, restUsername, restPassword);
String createGroupPayload =
""{"" +
"" \""groupName\"": \"""" + newGroupName + ""\"","" +
"" \""groupDescription\"": \"""" + newGroupDescription + ""\"","" +
"" \""groupStatus\"": \""OPEN\"","" +
"" \""isSecureGroup\"": \""false\"" "" +
""}"";
System.out.println(""Payload: "" + createGroupPayload);
Content c = Request.post(host + ""/api/user-groups"")
.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(createGroupPayload, null)
.execute().returnContent();
System.out.print(c.asString());
}
/*
* This function generates an access token for a user that will grant them access to
* call REST API endpoints.
*/
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 | ||||||
---|---|---|---|---|---|---|
| ||||||
using System.Net.Http.Headers;
using Newtonsoft.Json.Linq;
namespace rest.code.examples
{
public class CreateUserGroup
{
static async Task Main(string[] args)
{
string host = ""http://localhost:8080/Yellowfin"";
string restUsername = ""admin@yellowfin.com.au"";
string restPassword = ""test"";
string newGroupName = ""New Group"";
string newGroupDescription = ""This is a new group"";
string token = await GenerateToken(host, restUsername, restPassword);
string createGroupPayload = ""{"" +
"" \""groupName\"": \"""" + newGroupName + ""\"","" +
"" \""groupDescription\"": \"""" + newGroupDescription + ""\"","" +
"" \""groupStatus\"": \""OPEN\"","" +
"" \""isSecureGroup\"": \""false\"" "" +
""}"";
Console.WriteLine(""Payload: "" + createGroupPayload);
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(""YELLOWFIN"", ""ts="" + DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() + "" , nonce="" + new Random().NextInt64() + "", token="" + token);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(""application/vnd.yellowfin.api-v1+json""));
var content = new StringContent(createGroupPayload);
content.Headers.ContentType = new MediaTypeHeaderValue(""application/json"");
var response = await httpClient.PostAsync(host + ""/api/user-groups"", content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine(""Failed to create user group. Status code: "" + response.StatusCode);
}
}
}
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(
$""{{\""userName\"": \""{restUsername}\"", \""password\"": \""{restPassword}\""}}"",
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 = JObject.Parse(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 | ||||
---|---|---|---|---|
| ||||
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""
newGroupName := ""New Group""
newGroupDescription := ""This is a new group""
token, err := generateToken(host, restUsername, restPassword)
if err != nil {
fmt.Println(""Error generating token:"", err)
return
}
createGroupPayload := fmt.Sprintf(`{
""groupName"": ""%s"",
""groupDescription"": ""%s"",
""groupStatus"": ""OPEN"",
""isSecureGroup"": ""false""
}`, newGroupName, newGroupDescription)
fmt.Println(""Payload:"", createGroupPayload)
client := &http.Client{}
req, err := http.NewRequest(""POST"", host+""/api/user-groups"", bytes.NewBufferString(createGroupPayload))
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 | ||||||
---|---|---|---|---|---|---|
| ||||||
const fetch = require(""node-fetch"");
async function main() {
const host = ""http://localhost:8080/Yellowfin"";
const restUsername = ""admin@yellowfin.com.au"";
const restPassword = ""test"";
const newGroupName = ""New Group"";
const newGroupDescription = ""This is a new group"";
const token = await generateToken(host, restUsername, restPassword);
if (token === null) {
console.error(""Failed to retrieve access token"");
return;
}
const createGroupPayload = `{
""groupName"": ""${newGroupName}"",
""groupDescription"": ""${newGroupDescription}"",
""groupStatus"": ""OPEN"",
""isSecureGroup"": ""false""
}`;
console.log(""Payload:"", createGroupPayload);
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/user-groups`, {
method: 'POST',
headers: headers,
body: createGroupPayload
});
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 = `{
""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(); |
Java | C# | Go | JavaScript | PHP | Python
...