Github Rest api : what is the right value of Head field? - rest

I am trying to create a Pull Request, using curl . y
The pull request source and target branch are in the same repo. (Not cros repository).
The source branch name is cd/apim-1.25.27, and the target branch name is master.
I keep having the following error, and tried every possibility for the head field format (the PR source branch name), but still can’t get to create a the PR…
My curl :
curl \
-X POST \
-H "Accept: application/vnd.github.v3+json" \
-H "Authorization: token ******" \
https://api.github.com/repos/MY_ORGANIZATION/My_REPOSITORY/pulls \
-d '{"title":"Amazing new feature","body":"Please pull these awesome changes in!","head":"cd/apim-1.25.27","base":"master"}'
I got this message from github api
{
"message": "Validation Failed",
"errors": [
{
"resource": "PullRequest",
"field": "head",
"code": "invalid"
}
],
"documentation_url": "https://docs.github.com/rest/reference/pulls#create-a-pull-request"

I got the issue only using curl.
Creating the pull request with postman works well.
Finally I end up using octokit library, github official development kit (https://octokit.github.io/rest.js/v18#pulls-create).
Below the code I used:
const { Octokit } = require("#octokit/rest");
const octokit = new Octokit({auth: '${GITHUB_PAT_PR}' });
octokit.rest.pulls.create(
{
owner: 'OWNER',
repo: '${REPOSITORY_NAME}',
title: 'Creating new pull request',
body: 'Pull request detailled description',
head: 'source_branche',
base: 'destination_branch'
}).then(data => console.log("The pullrequest was successfuly created!"))
.catch(err => {
let reponseGithub = err.response.data.errors[0];
if(reponseGithub && reponseGithub.message && reponseGithub.message.includes("A pull request already exists for")) {
console.log("A pull request already exists for this repository");
}
else
{
console.log("An unexpected error occurred while creating the pull request on Github");
console.log("check octokit documentation ==> https://octokit.github.io/rest.js/v18#pulls-create ");
console.log("Github API Documentation ==> https://docs.github.com/rest/reference/pulls#create-a-pull-request ");
console.log(err.response.data.errors);
throw new Error('an error message');
}
});

Related

Upload large file to sharepoint site using Microsoft Graph via REST API

I'm trying to upload a file to a specific sharepoint site. In this page shows me how to upload a sample file to user's onedrive. But, in my case, I need to upload to sharepoint. I'm trying to use this endpoint:
POST /groups/{groupId}/drive/items/{itemId}/createUploadSession
But show me this error response:
{
"error": {
"code": "itemNotFound",
"message": "Item not found",
"innerError": {
"date": "2022-05-08T23:15:29",
"request-id": "ca4362ca-ff36-488c-80b1-9f82c3448cd5",
"client-request-id": "ca4362ca-ff36-488c-80b1-9f82c3448cd5"
}
}
This is cURL:
curl --request POST \
--url https://graph.microsoft.com/v1.0/groups/{groupId}/drive/items/test.txt/createUploadSession \
--header 'Authorization: Bearer xxxx' \
--header 'Content-Type: application/json' \
--data '{
"#microsoft.graph.conflictBehavior": "rename",
"description": "description",
"fileSize": 4,
"name": "test.txt"
}'
You are trying to call endpoint which requires itemId but you send file name instead of itemId.
POST /groups/{groupId}/drive/items/{itemId}/createUploadSession
Another way is to specify the path to the file. The item-path must contain the name of the item that's specified in the request body.
POST /groups/{groupId}/drive/root:/{item-path}:/createUploadSession
// file system path using /drive/root:/path/to/file
POST /groups/{groupId}/drive/root:/path/to/test.txt:/createUploadSession
Here is an example of uploading a large file to SharePoint using graph API SDK Read more, step-by-step solutions
public async Task<void> Upload()
{
string site = "<YOUR DOMAIN, REPLACE HERE>.sharepoint.com";
string relativePath = "/sites/<YOUR SITE, REPLACE HERE>";
var _authProvider = _SetAuthToken();
GraphServiceClient graphClient = new GraphServiceClient(_authProvider);
Site s = await graphClient
.Sites[site]
.SiteWithPath(relativePath)
.Request()
.GetAsync();
using (var fileStream =
System
.IO
.File
.OpenRead(
#"myfile.txt"
))
{
var uploadSession = await graphClient
.Sites[s.Id]
.Drive
.Root
.ItemWithPath("sometext-1.txt")
.CreateUploadSession()
.Request()
.PostAsync();
// Max slice size must be a multiple of 320 KiB
int maxSliceSize = 320 * 1024;
var fileUploadTask =
new LargeFileUploadTask<DriveItem>(uploadSession, fileStream,
maxSliceSize);
var totalLength = fileStream.Length;
// Create a callback that is invoked after each slice is uploaded
IProgress<long> progress = new Progress<long>(prog => { });
try
{ // Upload the file
var uploadResult = await fileUploadTask.UploadAsync(progress);
//Console.WriteLine(uploadResult.UploadSucceeded ?
// $"Upload complete, item ID: {uploadResult.ItemResponse.Id}" :
// "Upload failed");
}
catch (ServiceException ex)
{
//Console.WriteLine($"Error uploading: {ex.ToString()}");
}
}
}

How can I create a pull request with github api?

The API is : /repos/{owner}/{repo}/pulls.
I used the correct token, and the request body is :
data = {
"base": "master",
"head": "owner:master",
"title": "title",
}
The head is like this:
{'Accept': 'application/vnd.github.v3+json', "Authorization": "token {}".format(git_token)}
Then I call the pull API. Returned 200.
<Response [200]>
Why? Maybe the request body wrong?
The Pull Request API specified the answer:
Status: 201 Created
Try and anddapt their example to your repository, to see if it does work:
curl \
-X POST \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/repos/octocat/hello-world/pulls \
-d '{"head":"head","base":"base"}'

Get secret gists using Github GraphQL

As title, I'm using Github GraphQL explorer to fetch list of my gists.
query {
viewer {
gists(first:5, privacy:ALL) {
edges {
node {
id
description
name
pushedAt
}
}
}
}
}
Everything works fine except that the secret gists are not included in the response. When I tried to fetch secret gists by changing the GistPrivacy from ALL to SECRET as below:
query {
viewer {
gists(first:5, privacy:SECRET) {
edges {
node {
id
description
name
pushedAt
}
}
}
}
}
The following permission error occurred:
{
"data": {
"viewer": {
"gists": {
"edges": []
}
}
},
"errors": [
{
"message": "You don't have permission to see gists."
}
]
}
I wonder is there any way to solve this problem.
I noticed that there was a related questions with irrelevant answer asked 5 years ago.
Any comment or help is much appreciated, thanks in advance.
As it turns out, although one can't get the secret gists from the Github GraphQL explorer directly, by creating a Personal Access Tokens and using it to access the GraphQL API, one can get the secret gists.
The equivalent curl command is as following:
curl --request POST \
--url https://api.github.com/graphql \
--header 'authorization: Bearer YOUR_PERSONAL_ACCESS_TOKEN' \
--header 'content-type: application/json' \
--data '{"query":"query {\n viewer {\n gists(first:5, privacy:ALL) {\n\t\t\tedges {\n\t\t\t\tnode {\n\t\t\t\t\tid\n\t\t\t\t\tdescription\n\t\t\t\t\tname\n\t\t\t\t\tpushedAt\n\t\t\t\t}\n\t\t\t}\n\t\t}\n }\n}"}'

Integrating MATLAB with Google BigQuery via REST API

I'm trying to use MATLAB's webread function to query Google BigQuery via the REST API, and am having issues. The following curl request is successful:
curl 'https://www.googleapis.com/bigquery/v2/projects/<MyProjectId>/queries' \
-X POST \
-H 'Authorization: Bearer <MyBearerToken>' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
--data-binary '{"query":"select count(1) from MyTable","useLegacySql":false}' \
--compressed
However, the following MATLAB code:
api = 'https://www.googleapis.com/bigquery/v2/';
access_token = '<MyAccessToken>';
options = weboptions('RequestMethod', 'post');
r = webread([api 'projects/<MyProjectId>/queries?access_token=' access_token], ...
'query', 'select count(1) from MyTable', ...
'useLegacySql', false, ...
options);
generates the following error:
Error using readContentFromWebService (line 45)
The server returned the status 400 with message "Bad Request" in response to the request to URL
https://www.googleapis.com/bigquery/v2/projects/<MyProjectId>/queries?access_token=<MyAccessToken>&query=select+count(1)+from+<MyTable>&useLegacySql=0
Entering the URL in the MATLAB error into a POST requester shows the following (generic) error, so it appears the URL is malformed:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Required parameter is missing"
}
],
"code": 400,
"message": "Required parameter is missing"
}
}
How can I use MATLAB's webread to accomplish the same thing as the above curl request?
It turns out that the webread function doesn't have this functionality. This issue is resolved successfully by using webwrite as follows:
options = weboptions( ...
'RequestMethod', 'post', ...
'MediaType', 'application/json');
data = struct( ...
'query', 'select count(1) from MyTable', ...
'useLegacySql', false);
r = webwrite([api 'projects/<MyProjectId>/queries?access_token=' access_token], ...
data, ...
options);

how to create an issue in jira via rest api?

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.