I tried to add review comments by using this "set-review" api:
https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#set-review
I can get a json response from this interface, but nothing is changed.
I can't see any new comments from Gerrit web page.
Here is the example of my client side code:
url = '/changes/16148/revisions/1/review'
data = json.dumps({
'message': 'test',
'labels': {},
'comments': {
'tools/docpreview.py': [{
'line': 20,
'message': 'hehe',
}],
},
'notify': 'NONE'
})
pprint(rest.post(url, data=data))
And the response example(Private info was deleted).
This response looks like result of get-review api described here:
https://gerrit-review.googlesource.com/Documentation/rest-api-changes.html#get-review
{u'_number': 16148,
...
u'insertions': 20,
u'kind': u'gerritcodereview#change',
u'created': u'2014-11-05 16:23:08.849000000',
...
u'status': u'NEW',
u'subject': u'Add markdown preview.',
u'updated': u'2014-11-05 22:02:32.978000000'}
I struggled with getting this right for a while, finally, the following piece of code in Python works for me:
from requests.auth import HTTPBasicAuth
from pygerrit2.rest import GerritRestAPI
REST_AUTH = HTTPBasicAuth(MISC['auth_username'], MISC['auth_password'])
REST_CLIENT = GerritRestAPI(url=MISC['base_url'], auth=REST_AUTH)
query = "/changes/" + str(change_id) + "/revisions/" + str(cur_rev) + "/review"
REST_CLIENT.post(query, json={
"message": MISC['message'],
"reviewers": [{
"reviewer": MISC['reviewer_bot']
}]
})
# MISC is a dictionary
You should be authenticated, shouldn't you? Therefore your requests would have to go to /a/changes/
Related
I'm currently using Confluence server and I'm currently getting a 500 error when I try to create a new page using the REST API. I am currently using an HTML macro that makes GET & POST requests using the Fetch API. I currently have no issues when making GET requests, only issues with POST requests.
I tried researching the error and saw someone mention that they fixed it by turning off collaborative editing in the space, but in my case that is not an option. Anyone have an idea of what is causing this error?
function createPage() {
let url = "http://exampledomain:8090/confluence/rest/api/content/"
fetch(url, {
method: 'POST',
headers: {
'Authorization': 'Basic USER:PASS',
'Content-Type': 'application/json',
},
data: {
'type': 'page',
'title': "New Page",
'ancestors': [{ 'id': 97059352 }], // parent page id
'space': { 'key': "EXAMPLE_SPACE" },
'body': {
'storage': {
'value': "<h1>New Page!</h1>",
'representation': 'storage',
}
},
}
})
.then(response => console.log(response))
.catch(err => console.log(err.message))
}
I see invalid data structure:
'representation': 'storage', <== extra comma
}
}, <== another extra comma
}
Also double check with your programming language that you can use single quotes (') and that they are correctly transformed into double quotes ("). JSON (Jira REST API) accepts only double quotes for keys and string values.
I am learning web development and I am currently working on creating a lambda test application for stripe. The paymentMethod id from the front-end is not being detected by my lambda function when I run it locally by calling sam local start-api. I am doing my development on VS Code.
I followed the instructions on this page to create and run my application. My directory structure looks like this:
hello_world/app.py has my Lambda function.
The code for invoking the lambda end-point in script.jslooks like this:
var stripe = Stripe('pk_test_DIGITS');
var elements = stripe.elements();
form.addEventListener('submit', function(event) {
// We don't want to let default form submission happen here,
// which would refresh the page.
event.preventDefault();
stripe.createPaymentMethod({
type: 'card',
card: cardElement,
billing_details: {
// Include any additional collected billing details.
name: 'Jenny Rosen',
},
}).then(stripePaymentMethodHandler);
});
function stripePaymentMethodHandler(result) {
if (result.error) {
// Show error in payment form
} else {
// Otherwise send paymentMethod.id to your server (see Step 4)
fetch('http://127.0.0.1:3000/payment', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
payment_method_id: result.paymentMethod.id,
})
}).then(function(result) {
// Handle server response (see Step 4)
result.json().then(function(json) {
handleServerResponse(json);
})
});
}
}
I ran the application on the browser by doing this:
When I click on Pay from my browser I can see the response in the logs on my dashboard:
The following code is for my lambda function app.py:
import json
import stripe
import requests
import logging
stripe.api_key= "sk_test_DIGITS"
def process_payment(event, context):
try:
print("START PRINTING")
print(event)
print("END PRINTING")
intent = stripe.PaymentIntent.create(
payment_method = 'event["body"]["payment_method_id"]',
amount = 1555,
currency = 'usd',
confirmation_method = 'automatic',
confirm = True,
payment_method_types=["card"]
)
return {
"statusCode": 200,
"body": json.dumps({
'clientSecret': intent['client_secret'],
# "location": ip.text.replace("\n", "")
}),
}
except Exception as e:
return {
"statusCode": 400,
"body": json.dumps({
"message": str(e),
# "location": ip.text.replace("\n", "")
}),
}
My template.yaml is as follows:
Globals:
Function:
Timeout: 30
Resources:
StripePaymentProcessor:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.process_payment
Runtime: python3.6
Events:
Payment:
Type: Api
Properties:
Path: /payment
Method: post
Outputs:
HelloWorldApi:
Description: "API Gateway endpoint URL for Prod stage for Payment function"
Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/payment/"
HelloWorldFunction:
Description: "Payment Lambda Function ARN"
Value: !GetAtt StripePaymentProcessor.Arn
HelloWorldFunctionIamRole:
Description: "Implicit IAM Role created for Payment function"
Value: !GetAtt StripePaymentProcessorRole.Arn
While keeping the browser window open, I ran the sam build command and it worked properly. After that I ran the sam local invoke command and it produced the following output:
I do not understand why event is empty. Should it not show the JSON data that got produced when I hit the pay button?
To do some trouble-shooting, I ran sam local start-api, invoked the POST method on Postman by pasting the JSON body from my Stripe logs:
What I did on Postman makes no sense to me and the snippet above raised another question for me. I do not understand why I see "message": "string indices must be integers" as a response on Postman.
EDIT:
After following wcw's suggestion I edited my fetch code to look like this:
I did not not see any written matter on the console by changing my code in this way.
I am keeping the browser open via the command prompt and I ran sam local start-api via the VS code console to keep http://127.0.0.1:3000/payment open. When I clicked on the pay button, I got the following response:
So the image above seems to indicate that the lambda function is not detecting the paymentmethod body.
I`m trying to get the token from the spotify API, I use axios. I use the example given by the API as a guide, but give me the error 404
export const getToken = code => async dispatch => {
const responseToken = await axios.post({
url: "https://accounts.spotify.com/api/token",
form: {
grant_type: "authorization_code",
code,
redirect_uri
},
headers: {
'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
},
json: true
})
console.log(responseToken);
The first line is because I`m using redux,I just wanted you to see that it was a asinc method.
I have being all day trying to fix this, I don`t have more ideas of how to solve this
Try changing
form: {
grant_type: "authorization_code",
code,
redirect_uri
}
to
data: JSON.stringify({
grant_type: "authorization_code",
code,
redirect_uri
})
You want to send it in the request body, hence "data", that's how you define it in axios.
Also, I don't think you need json: true
EDIT:
Pretty sure you have to add 'content-type': 'application/x-www-form-urlencoded;charset=utf-8' to the headers as well.
I am trying to create issues in a Github repo via a Javascript client. My code is like so
const github = `https://api.github.com/repos/${owner}/${repo}/issues`;
const msg = JSON.stringify({
"title": `problem with record id: ${recId}`,
"body": "something is wrong in Houston",
"assignee": "flooba",
"milestone": 1,
"labels": [
"images"
]
});
const x = new XMLHttpRequest();
x.open('POST', github, true);
x.onreadystatechange = function() {
if (x.readyState == 4) {
// show status message, all good
}
};
x.setRequestHeader("Content-type", "application/json");
x.setRequestHeader("Authorization", "Basic " + btoa("username:password")); //**
x.send(msg);
[**] username and password are the creds for the :repo, naturally.
When I try the above code, I get http 422. Suggestions?
Note: In the actual working code, I will put the credentials on the server side and invoke the server side process from the web client.
I'm trying to post with POSTMAN to the new IBM Watson work services but only get one error after the other.
This documentation does not clearly explain the body scheme for messages (or does it?):
https://workspace.ibm.com/developer/docs#genericannotation
So I'm guessing around:
POST to
https://api.watsonwork.ibm.com/v1/spaces/{spaceId}/messages
With headers:
Content-Type:application/json
Authorization:Basic 123456789
spaceId: MySpaceID
body:{"input": {"text": "Hello"}}
What's the right scheme for the body to post that message with success?
I always get the following error:
{
"timestamp": "2016-10-27T12:53:07.134+0000",
"status": 403,
"error": "Forbidden",
"message": "No message available",
"path": "/teams/{spaceId}/messages"
}
I create a Script on GitHub, you can have more details on file PostMessageOnWatsonWorkspace.py
I put part of the code below
appname = 'PostMessageOnWatsonWorkspace'
text = """
Visit [IBM site](http://www.ibm.com), and leave a *message*.
Have _fun_!!!
Code Line:
`code`
Code Block:
```
code block
```
Bye
"""
Currently to format has only Bold, Italic, Code and links.
And this is an example of Post data.
data = {
'type': 'appMessage',
'version': 1.0,
'annotations': [{
'type': 'generic',
'version': 1.0,
'color': '#4FC3F7',
'title': appname + ' --> sendRichMessage at ' + str(datetime.datetime.now()),
'text': text,
'actor': {
'name': 'Enio Basso',
'avatar': '',
'url': 'https://ebasso.net'
}
}]
}
Other details you can find on documentation.