Clockify - Best way to get ALL data into excel or access using the REST api? - rest

I am trying to get all data into excel using the Get data from web option but I am not sure how to properly configure it. I did get the API key.
EDIT:
Below is the path I use, but that is only the time entries for one user, I need them for ALL users.
https://api.clockify.me/api/v1/workspaces/myWorkspace/user/myUser/time-entries
Any help is appreciated.

EDIT: I didn't read that you wanted to use Power Query in Excel. The Advanced Editor only works with this code in Power BI Desktop.
You'll need to program the request in the Advanced Editor in Power Query.
Here is an example of connecting to the Get Workspace Clients endpoint:
let
baseUrl = "https://api.clockify.me/api/v1/",
apiKey = "your-api-key",
workspaceID = "5dfb421c1b30342708229760",
GetWorkspace = (workspaceID as text) =>
let
options = [Headers = [#"X-Api-Key"= apiKey, #"Content-Type" = "application/Json"],
RelativePath = "workspaces/" & workspaceID & "/clients"],
call = Web.Contents(baseUrl, options),
jsonParsed = Json.Document(call)
in
jsonParsed
in
GetWorkspace
Using this function you just have to change the parameters you need according to the endpoint you want to hit.
The baseUrl will be the same, you'll need to change the RelativePath with the rest of the url and if you need to pass some query parameters, put them after RelativePath in a record, like this:
RelativePath = "workspaces/" & workspaceID & "/clients", Query = [page = "1"]],
I recommend using Postman to make the calls and Fiddler to track how the Url is being constructed. Then compare Postman requests with your power query requests, to check the differences.
Here are some other threads about the subject:
How to access Clockify API through Power Query
How to pull data from Toggl API with Power Query?

Related

create or update a panel in Grafana using Python

I have a dashboard named as "server-plots" and there is another dashboard named as "master-plots". panels under "master-plots" are most updated graphs and I want to add the new panels inside "master-plots" dashboard to "server-plots" as well, everything with Python code (not manually or using curl).
I am able to programmatically take the backup of these plots using Grafana GET APIs ,as JSON. I want to find the new panels inside the "master-plots" dashboard JSON and add those into "server-plots" dashboard , all using Python. I am unable to find any API to do that. Any idea how can I achieve this?
The way I achieved this was by taking the backup of the master-plots as JSON using:
/api/dashboards/uid/<uid of the dashboard>
Then comparing it with the one inside the server-plots (taken similarly), and then updating the server-plots JSON with the diff (basically replacing server-plots JSON with the master-plots JSON), and finally writing that to the following using the POST method:
/api/dashboards/db/
One thing to consider here: The new JSON which is being written into the server-plots should have different uid and overwrite=True:
--snip--
f = open(myjsonfile,) # the updated JSON of server-plots
data = json.load(f)
data["dashboard"]["id"] = None
data["overwrite"] = True
data["folderId"] = 123 # this is the folder ID of the server-plots
data["dashboard"]["uid"] = <logic to generate randum alpha-num>
url = "https://mygrafanaurl.com/api/dashboards/db"
headers = {'Authorization': 'auth', 'Content-Type': 'application/json' }
response = requests.request("POST", url, headers=headers, data=json.dumps(data))

PowerQuery missing supports for windows authentification and REST API POST body

I've discovered the hard way that PowerQuery (Powerbi & excel) Web.Contents function doesn't support a body payload when using Windows authentification.
with similar query
let
body = "{""json"" : ""payload""}",
Data= Web.Contents("http://xxxx/api/Query",[Content=Text.ToBinary(body),Headers=[#"Content-Type"="application/json"]]),
DataRecord = Json.Document(Data)
...
pretty stocked this lonely support and I suspect I'm missing an important aspect. Is there a recommanded way ? My google search were pretty un-successful.
Should I generate some kind of token with a first GET and then make a POST with body + token in anonymous ?
Do you have to use Windows authentication? How about using something like this with Anonymous authentication:
let
AuthKey = "mytoken",
url="http://xxxx/api/Query",
body = "{""json"" : ""payload""}",
Source = Json.Document(Web.Contents(url,[
Headers = [#"Authorization"=AuthKey ,
#"Content-Type"="application/json"],
Content = Text.ToBinary(body)
]
))
in
Source
Will this solve your problem?

How to get the last login session details of a user in Keycloak using Keycloak rest endpoints?

How to get the last login session details of a user in Keycloak using keycloak rest endpoints?
Example:
builder.append(OAuth2Constants.AUDIENCE+"="+clientId+"&");
builder.append(OAuth2Constants.GRANT_TYPE+"="+OAuth2Constants.UMA_GRANT_TYPE+"&");
headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("Authorization", "Bearer "+accessToken);
//String keycloakURL = keyCloakCFGBean.getCreateRefreshSession();
String keycloakURL="http://10.10.8.113:10004/auth/realms/{realm}/protocol/openid-connect/token";
keycloakURL = keycloakURL.replace("{realm}", realmName);
URL url = new URL(keycloakURL);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
if (headers != null && headers.size() > 0) {
Iterator<Entry<String, String>> itr = headers.entrySet().iterator();
while (itr.hasNext()) {
Entry<String, String> entry = itr.next();
httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream(), StandardCharsets.UTF_8);
outputStreamWriter.write(builder.toString());
outputStreamWriter.flush();
So there are a couple of scenarios here. All of this information assumes that you have an appropriate bearer token that you are sending in the header of the request for authentication/authorisation, and requires that you have sufficient admin privileges in the Keycloak realm.
I've not gone into detail in terms of the precise code you write in a particular language, but hopefully the instructions are clear in terms of what you need your code to do.
Sessions
If you are interested in ACTIVE user sessions specifically, you can use the API endpoint as described at: https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_getsessions
That is:
GET /{realm}/users/{id}/sessions
e.g. the full URL would be:
https://{server}/auth/admin/realms/{realm}/users/{id}/sessions
In the response there will be a property called lastAccess that will contain a number that is the usual UNIX milliseconds since 1/1/1970. If you take that number, you can then parse it in your language of choice (Java from the looks of it?) to get the date/time in the format that you require.
All Logins
However I suspect what you really want is to look at the last login across all of the stored information in Keycloak, not just active user sessions, so for that you need to look for the Realm EVENTS. Note that Keycloak only stores events for a certain amount of time, so if it's older than that then you won't find any entries. You can change how long events are stored for in the events config page of the realm admin console.
To get all realm events you call the endpoint mentioned here: https://www.keycloak.org/docs-api/11.0/rest-api/index.html#_getevents (Search for "Get events Returns all events, or filters them based on URL query parameters listed here" if the link doesn't take you straight there).
i.e.
GET /{realm}/events
e.g. the full URL would be: https://{server}/auth/admin/realms/{realm}/events
You will need to filter the results based on "type" (i.e. so that you only have events of type "LOGIN"), and if you want to check a specific user you would also want to filter the results on userId based on the ID of that user account.
You can perform both of these filters as part of the request, to save you having to get the full list of events and filter it client-side. To filter in the request you do something like the following:
https://{server}/auth/admin/realms/{realm}/events?type=LOGIN&user={id}
From the resultant JSON you can then get the result with the highest value of the time property, that represents that login event. The time property will be a UNIX time of milliseconds since 1/1/1970 again, so again you can convert this to a format that is appropriate to you once you have it.
Hope that's helpful!
use Keycloak rest Api
${keycloakUri}/admin/realms/${keycloakRealm}/users
and you will get a response as JWT. Decode it and you will get all the info related to the user.
OR you may use the java client API for example by
Keycloak kc = KeycloakBuilder.builder()
.serverUrl("https://localhost:8443/auth")
.realm("master")
.username("admin")
.password("admin")
.clientId("Mycli")
.resteasyClient(new ResteasyClientBuilder().connectionPoolSize(10).build())
.build();
CredentialRepresentation credential = new CredentialRepresentation();
credential.setType(CredentialRepresentation.PASSWORD);
credential.setValue("test123");
UserRepresentation user = new UserRepresentation();
user.setUsername("testuser2");
user.setFirstName("Test2");
user.setLastName("User2");
user.setEmail("aaa#bbb.com");
user.setCredentials(Arrays.asList(credential));
user.setEnabled(true);
user.setRealmRoles(Arrays.asList("admin"));
UsersResource usersResource = kc.realm("my-realem").users();
UserResource userResource = usersResource.get("08afb701-fae5-40b4-8895-e387ba1902fb");
you will get the list of users. Filter by user ID then you will find all user info.

Invalid_request_parameter (create and sending envelopes)

I'm trying to use a service of DocuSign API in an abap project. I want to send a document to a specific email so it can be signed. But im getting the following error:
"errorCode": "INVALID_REQUEST_PARAMETER",## "message": "The request contained at least one invalid parameter. Query parameter 'from_date' must be set to a valid DateTime, or 'envelope_ids' or 'transaction_ids' must be specified.
I tried the following:
CALL METHOD cl_http_client=>create_by_url
EXPORTING
url = l_url (https://demo.docusign.net/restapi/v2/accounts/XXXXXX')
proxy_host = co_proxy_host
proxy_service = co_proxy_service
IMPORTING
client = lo_http_client
lo_http_client->request->set_method( method = 'POST').
CALL METHOD lo_http_client->request->set_header_field
EXPORTING
name = 'Accept'
value = 'application/json'.
CALL METHOD lo_http_client->request->set_header_field
EXPORTING
name = 'X-DocuSign-Authentication'
value = get_auth_header( ). (json auth header)
CALL METHOD lo_http_client->request->set_cdata
EXPORTING
data = create_body( ).
This is my body:
CONCATENATE
`{`
`"emailSubject": "DocuSign REST API Quickstart Sample",`
`"emailBlurb": "Shows how to create and send an envelope from a document.",`
`"recipients": {`
`"signers": [{`
`"email": "test#email",`
`"name": "test",`
`"recipientId": "1",`
`"routingOrder": "1"`
`}]`
`},`
`"documents": [{`
`"documentId": "1",`
`"name": "test.pdf",`
`"documentBase64":` `"` l_encoded_doc `"`
`}],`
`"status": "sent"`
`}` INTO re_data.
The api request to get the Baseurl is working fine. (I know the error is quite specific what the problem is, but i cant find any sources on the docusign api documentation that one of the mentioned parameters should be added to the request)
Thank you in regards
The error message seems to indicate that you're Posting to an endpoint that requires certain query string parameters -- but you're not specifying them as expected in the query string. I'd suggest you check the DocuSign API documentation for the operation you are using, to determine what query string parameters it requires, and then ensure that you're including those parameters in your request URL.
If you can't figure this out using the documentation, then I'd suggest that you update your post to clarify exactly what URL (endpoint) you are using for the request, including any querystring parameters you're specifying in the URL. You can put fake values for things like Account ID, of course -- we just need to see the endpoint you are calling, and what qs params you're sending.
To create an envelope, use
https://demo.docusign.net/restapi/v2/accounts/XXXXXX/envelopes
instead of
https://demo.docusign.net/restapi/v2/accounts/XXXXXX
Thank you for all the answers, i found the mistake. Creating the request wasn´t the problem. I was using the wrong "sending"-method -_-.
now its working :)
lo_rest_client->post( EXPORTING io_entity = lo_request_entity ).

elastic search: How to retrieve the indexed data

In elastic search java api, suppose I am building the indexed data using this client
Node node = nodeBuilder().clusterName("es").node();
Client client = node.client();
IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
.setSource(jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elasticsearch")
.endObject()
)
.execute()
.actionGet();
This indexed data is stored in folder XYZ/elasticsearch/data.
My question is how to retrieve this indexed data in java from some other client or some other code. Is there any way in which I can give the path and the already indexed data can be imported, then I can perform queries on it?
Edit :
The code for client on other computer
Node node = nodeBuilder().clusterName("es").node();
Client client = node.client();
MatchQueryBuilder qb = QueryBuilders.matchQuery("user", "kimchy");
SearchRequestBuilder srb = client.prepareSearch("twitter").setTypes("tweet");
SearchResponse big = srb.setQuery(qb).execute().actionGet();
SearchHit[] results = big.getHits().getHits();
This shows
search.SearchPhaseExecutionException: Failed to execute phase [query], all shards failed
Thanks
Arya
I'm not sure I understand the question, but if it's just querying in java here's an example :
MatchQueryBuilder qb = QueryBuilders.matchQuery("user", "kimchy);
SearchRequestBuilder srb = client.prepareSearch("twitter").setTypes("tweet");
srb.setQuery(qb);
SearchResponse response = srb.execute().actionGet();
//Here goes your code where you use response.getHits() that contains your items
The message you get by using my snippet usually indicates that your client doesn't manage to connect to your server. Check your server status (i.e. that you launched your server properly) and try using this.
Node node = NodeBuilder.nodeBuilder().client(true).node();
client = node.client();
I don't think you need to specify the clustername unless you have some custom configuration i'm not aware of. Also check your index name.