I'm learning both Grafana, AND how to interact with APIs in Powershell. I was able to use the Grafana HTTP API to create a dashboard, however I cannot get the same API to create a Datasource. My code is as follows:
$header = #{"Authorization" = "Bearer apikey="}
$createDatasourceUri = "http://localhost:3000/api/datasources"
$createDatasourcejson = #'
{
"datasource": {
"name": "prometheusApiTest",
"type": "prometheus",
"url": "http://localhost:9090",
"access": "proxy",
"basicAuth": false,
"isDefault": true
}
}
'#
$datasourceParameters = #{
Method = "POST"
URI = $createDatasourceUri
Body = $createDatasourcejson
Headers = $header
ContentType = "application/json"
}
Invoke-RestMethod #datasourceParameters
I am presented with the following error:
Invoke-RestMethod : [{"fieldNames":["Name"],"classification":"RequiredError","message":"Required"},{"fieldNames":["Type"],"classification":"RequiredError","message":"Required"},{"fieldNames":["Access"],"classificat
ion":"RequiredError","message":"Required"}]
I do not know what's going on. Anything I can find about this error says I need to specify the ContentType as "application/json", but I've very clearly done so. I do receive data when I do a "GET" on that API endpoint, and even copying the data that gets returned still results in the above error. I'm at a complete loss, as this same code worked to create a dashboard (albeit with the right json payload for a dashboard). Any ideas?
The Grafana docs for the Datasource API only has the datasource element in the response, not the initial call. Line 5 of my code, and the subsequent {} for that element, are not needed, and the script functions with those lines removed.
Related
Trying to import a private GitHub repository into Azure DevOps using the REST API:
https://learn.microsoft.com/en-us/rest/api/azure/devops/git/import%20requests/create?view=azure-devops-rest-6.0
Unsurprisingly, the documentation doesn't work.
I have a PAT based service endpoint in the DevOps project that has access to the GitHub repository I'm trying to import.
I have the following PowerShell snippet that reproduces the problem
$headers = #{
Authorization = "Bearer ****"
}
$org = '***'
$project = '***'
$targetRepositoryId = '***'
$sourceRepositoryUrl = '***'
$gitHubServiceEndpointId = '***'
irm https://dev.azure.com/$org/$project/_apis/git/repositories/$targetRepositoryId/importRequests?api-version=6.0-preview.1 -Method Post -Headers $headers -ContentType application/json -Body #"
{
"parameters": {
"gitSource": {
"overwrite": false,
"url": "$sourceRepositoryUrl"
},
"serviceEndpointId": "$gitHubServiceEndpointId",
"deleteServiceEndpointAfterImportIsDone": false
}
}
"#
Throws a 400 error (Bad Request) with no additional information.
If I make the GitHub repository public, the exact same API request and the exact same code above works fine.
I am also 100% certain that the service endpoint has access to the repository in question because I have pipelines in Azure DevOps that use this service endpoint to clone said repository from GitHub.
I was able to get the import to work using a GitHub service connection ONLY if you create the service connection using UsernamePassword authorization scheme -- which you can't do from DevOps itself you have to do from the API:
irm "https://dev.azure.com/org/project/_apis/serviceendpoint/endpoints?api-version=6.0-preview.1" -Method Post -Headers $headers -ContentType application/json -Body #"
{
"authorization": {
"scheme": "UsernamePassword",
"parameters": {
"username": "foo",
"password": "github access token"
}
},
"name": "Test-5",
"serviceEndpointProjectReferences": [
{
"description": "",
"name": "Test-5",
"projectReference": {
"id": "project id",
"name": "projectName"
}
}
],
"type": "github",
"url": "https://github.com",
"isShared": false,
"owner": "library"
}
"#
According to captured network log, the service connection type needs to be "Other Git" when create the service connection, then input Git repository URL and Personal access tokens created in GitHub:
With this service connection ID, it's supposed to be able to get a successful import.
I am new to Robot Framework and am facing an issue while sending query params in Get Request method.
Following is the code that I tried with no luck :
Get Data With Filter
[Arguments] ${type} ${filter}
${auth} = Create List ${user_name} ${password}
${params} = Create Dictionary type=${type} filter=${filter}
Create Session testingapi url=${some_host_name} auth=${auth}
${resp} = Get Request testingapi /foo/data params=${params}
Log ${resp}
${type} has value new and ${filter} that I want is id:"1234"
I am expecting final url to formed as :
/foo/data?type=new&filter=id%3A1234
Instead of forming the expected url, I get the request url as :
GET Request using : uri=/foo/data, params={'type': 'new', 'filter': 'id:1234'}
I might be missing something very obvious but I cant figure out what it is. What can I change in this piece of code or any new code that needs to be added?
I think the logger is just outputting the params as the dictionary. The request should actually be made to foo/data?type=new&filter=id%3A1234
You can test it with the following request to Postman Echo (An HTTP testing service):
${auth} = Create List Mark SuperSecret
${params} = Create Dictionary type=Condos filter=2Bedrooms
Create Session testingapi url=http://postman-echo.com auth=${auth}
${resp} = Get Request testingapi /get params=${params}
${json} = To JSON ${resp.content} pretty_print=True
Log \n${json} console=yes
The response will correctly list the params you've encoded:
{
"args": {
"filter": "2Bedrooms",
"type": "Condos"
},
"headers": {
"accept": "*/*",
"accept-encoding": "gzip, deflate",
"authorization": "Basic TWFyazpTdXBlclNlY3JldA==",
"host": "postman-echo.com",
"user-agent": "python-requests/2.25.0",
"x-amzn-trace-id": "Root=1-5fb43ae9-1880b0a621c864b06ce1f54a",
"x-forwarded-port": "80",
"x-forwarded-proto": "http"
},
"url": "http://postman-echo.com/get?type=Condos&filter=2Bedrooms"
}
currently i'm attempting to setup GoPhish to launch campaigns through a Windows PowerShell script using it's API. The issue that i'm running into that is i'm getting this error.
Invoke-WebRequest : { "message": "Invalid JSON structure", "success": false, "data": null }
The thing is I have triple checked my JSON structure and it doesn't show any errors in JSON formatting checkers. So my question is if there are any errors in the code I have below for actually pushing these campaigns via PowerShell.
$jsonString = #"
{
"name":"Test6",
"template":{
"name":"Test"
},
"url":"http://redacted",
"page":{
"name":"Test"
},
"smtp":{
"name":"Test SMTP"
},
"launch_date":"2019-25-07T08:20:00+00:00",
"send_by_date":null,
"groups":{
"name":"Test Group"
}
}
"#
Invoke-WebRequest -Uri https://redacted/api/campaigns/?api_key=redacted -Method POST -Body $jsonString
So if you see any errors in what I have an could help me out, that'd be awesome. The API documentation shows that it should be in this format
{
"name":"CC Example Campaign",
"template":{"name":"Example Template"},
"url":"http://localhost",
"page":{"name":"Example Landing Page"},
"smtp":{"name":"Example Sending Profile"},
"launch_date":"2018-10-08T16:20:00+00:00",
"send_by_date":null,
"groups":[{"name":"Example Group"}]
}
I have following code I am trying to run in IBM function to get billing data out:
iam_token = 'Bearer eyJraWQiOiIyMDE3MTAzMC0wM****'
def processResourceInstanceUsage(account_id, billMonth):
METERING_HOST = "https://metering-reporting.ng.bluemix.net"
USAGE_URL = "/v4/accounts/"+account_id + \
"/resource_instances/usage/"+billMonth+"?_limit=100&_names=true"
url = METERING_HOST+USAGE_URL
headers = {
"Authorization": "{}".format(iam_token),
"Accept": "application/json",
"Content-Type": "application/json"
}
response = requests.get(url, headers=headers)
print("\n\nResource instance usage for first 100 items")
return response.json()
processResourceInstanceUsage('*****', '11')
For some reason, I keep on getting 201 unauthorized error. I tried creating iam_token many times. It still gives the same error.
There are few things that should be taken care in the code you provided.
The month you are passing is wrong. It should be in YYYY-MM format.
account_id should be the id next to your Account name when you run ibmcloud target
For IAM token, run this command ibmcloud iam oauth_tokens. If you want to generate access token using your Platform API Key, refer to this link. The word Bearer is not required as this is not an authorization token.
Once you have all this in place, create an IBM Cloud function (Python 3), add the below code, pass the account_id and token and invoke the action to see the result . IBM Cloud function expects a dictionary as an input/parameter and JSON as response
import sys
import requests
def main(dict):
METERING_HOST="https://metering-reporting.ng.bluemix.net"
account_id="3d40d89730XXXXXXX"
billMonth="2018-10"
iam_token="<IAM_TOKEN> or <ACCESS_TOKEN>"
USAGE_URL="/v4/accounts/"+account_id+"/resource_instances/usage/"+billMonth+"?_limit=100&_names=true"
url=METERING_HOST+USAGE_URL
headers = {
"Authorization": "{}".format(iam_token),
"Accept": "application/json",
"Content-Type": "application/json"
}
response=requests.get(url, headers=headers)
print ("\n\nResource instance usage for first 100 items")
return { 'message': response.json() }
This worked for me and returned a JSON with region-wise billing data.
Reference: https://stackoverflow.com/a/52333233/1432067
Is it possible to create an issue in jira using REST api? I didn't find this in the documentation (no POST for issues), but I suspect it's possible.
A wget or curl example would be nice.
POST to this URL
https://<JIRA_HOST>/rest/api/2/issue/
This data:
{
"fields": {
"project":
{
"key": "<PROJECT_KEY>"
},
"summary": "REST EXAMPLE",
"description": "Creating an issue via REST API",
"issuetype": {
"name": "Bug"
}
}
}
In received answer will be ID and key of your ISSUE:
{"id":"83336","key":"PROJECT_KEY-4","self":"https://<JIRA_HOST>/rest/api/2/issue/83336"}
Don't forget about authorization. I used HTTP-Basic one.
The REST API in JIRA 5.0 contains methods for creating tasks and subtasks.
(At time of writing, 5.0 is not yet released, although you can access 5.0-m4 from the EAP page. The doco for create-issue in 5.0-m4 is here).
As of the latest released version (4.3.3) it is not possible to do using the REST API. You can create issues remotely using the JIRA SOAP API.
See this page for an example Java client.
This is C# code:
string postUrl = "https://netstarter.jira.com/rest/api/latest/issue";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("JIRAMMS:JIRAMMS"));
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = #"{""fields"":{""project"":{""key"": ""JAPI""},""summary"": ""REST EXAMPLE"",""description"": ""Creating an issue via REST API 2"",""issuetype"": {""name"": ""Bug""}}}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
To answer the question more direct, i.e. using cURL.
To use cURL to access JIRA REST API in creating a case, use
curl -D- -u <username>:<password> -X POST --data-binary "#<filename>" -H "Content-Type: application/json" http://<jira-host>/rest/api/2/issue/
And save this in your < Filename> (please edit the field per your Jira case) and save in the folder you call the cURL command above.
{
"fields": {
"project":
{
"key": "<PROJECT_KEY>"
},
"summary": "REST EXAMPLE",
"description": "Creating an issue via REST API",
"issuetype": {
"name": "Bug"
}
}
}
This should works. (note sometimes if it errors, possibly your content in the Filename is incorrect).
Now you can use REST + JSON to create issues.
To check which json fields you can set to create the issue use:
https://jira.host.com/rest/api/2/issue/createmeta
For more information please see the JIRA rest documentation:
https://docs.atlassian.com/jira/REST/6.2.4/
To send the issue data with REST API we need to construct a valid JSON string comprising of issue details.
A basic example of JSON string:
{“fields” : { “project” : { “key” : “#KEY#” } , “issuetype” : { “name” : “#IssueType#” } } }
Now, establish connection to JIRA and check for the user authentication.
Once authentication is established, we POST the REST API + JSON string via XMLHTTP method.
Process back the response and intimate user about the success or failure of the response.
So here JiraService being an XMLHTTP object, something like this will add an issue, where EncodeBase64 is a function which returns encrypted string.
Public Function addJIRAIssue() as String
With JiraService
.Open "POST", <YOUR_JIRA_URL> & "/rest/api/2/issue/", False
.setRequestHeader "Content-Type", "application/json"
.setRequestHeader "Accept", "application/json"
.setRequestHeader "Authorization", "Basic " & EncodeBase64
.send YOUR_JSON_STRING
If .Status <> 401 Then
addJIRAIssue = .responseText
Else
addJIRAIssue = "Error: Invalid Credentials!"
End If
End With
Set JiraService = Nothing
End Sub
You can check out a complete VBA example here
In order to create an issue, set a time estimate and assign it to yourself, use this:
Generate an Atlassian token
Generate & save a base64-encoded auth token:
export b64token="$(echo "<your_email>:<generated_token>" | openssl base64)"
Make a POST request:
curl -X POST \
https://<your_jira_host>.atlassian.net/rest/api/2/issue/ \
-H 'Accept: */*' \
-H 'Authorization: Basic $b64token \
-d '{
"fields":{
"project":{
"key":"<your_project_key (*)>"
},
"issuetype":{
"name":"Task"
},
"timetracking":{
"remainingEstimate":"24h"
},
"assignee":{
"name":"<your_name (**)>"
},
"summary":"Endpoint Development"
}
}'
Remarks:
(*) Usually a short, capitalized version of the project description such as: ...atlassian.net/projects/UP/.
(**) if you don't know your JIRA name, cURL GET with the same Authorization as above to https://<your_jira_host>.atlassian.net/rest/api/2/search?jql=project=<any_project_name> and look for issues.fields.assignee.name.
Just stumbling on this and am having issues creating an issue via the REST API.
issue_dict = {
'project': {'key': "<Key>"},
'summary': 'New issue from jira-python',
'description': 'Look into this one',
'issuetype': {'name': 'Test'},
}
new_issue = jira.create_issue(issue_dict)
new_issue returns an already existing issue and doesn't create one.