lua - How to send POST data properly using luasec? - post

I'm trying to POST some json datas in lua with luasec, but while following examples, it looks like no data is sent. It occurs even with GET requests. Maybe I'm not using ltn12 correctly ?
Here is the code I tried :
local ltn12 = require('ltn12')
local https = require('ssl.https')
local json = require("json")
local body = json.encode({
test = "test ok"
})
local r = {}
https.request {
url = 'https://httpbin.org/anything',
method = "POST",
headers = {["Content-Type"] = "application/json"},
source = ltn12.source.string(body),
sink = ltn12.sink.table(r)
}
print(r[1])
And here's the result :
{
"args": {},
"data": "",
"files": {},
"form": {},
"headers": {
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "LuaSocket 3.0-rc1",
"X-Amzn-Trace-Id": "..."
},
"json": null,
"method": "POST",
"origin": "XX.XX.XX.XX",
"url": "https://httpbin.org/anything"
}
The "data" field is empty.

Answering myself, problem solved. It is not a luasec issue, things are similar with socket.http.
The body sent has "content-type: application/json", so the data is in json field, not in data field.
headers needs a size of the datas
So the correct code is :
local ltn12 = require('ltn12')
local https = require('ssl.https')
local json = require("json")
local body = json.encode({
test = "test ok"
})
local r = {}
https.request {
url = 'https://httpbin.org/anything',
method = "POST",
headers = {
["Content-Type"] = "application/json",
["Content-Length"] = #body
},
source = ltn12.source.string(body),
sink = ltn12.sink.table(r)
}
print(r[1])

Related

Adding an image as an attachment to an Azure DevOps work item using the "Attachments - Create" API does not render when opened

I've gone through several other SO pages and while it did help me with understanding how the upload of attachments to work item works, I still cannot find a way to view the said attachment after successfully uploading it via API, especially if its an image.
APIs I've used:
To create an attachment link: https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/attachments/create?view=azure-devops-server-rest-5.0
Using the attachment URL retrieved from the previous API response, I use it in the Work Item Update API, below is a snippet:
api = f"https://dev.azure.com/{organization}/_apis/wit/workitems/{work_item_id}?api-version=6.0"
file_size = os.path.getsize(file_path)
payload = [
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
"url": attachment_url,
"attributes": {
"comment": "Test",
"resourceSize": file_size
}
}
}
]
After this, the attachment is visible in the work item but when clicked on, it does not render the image. Instead a window opens and an infinite loading screen animation plays.
Its got to be the encoding of the image thats causing this however I cannot find any documentation.
Below is the full code for uploading attachments to an existing work item.
def upload_attachment(file_path, work_item_id):
# This part retrieves the Attachment URL
headers = {
"Accept": "application/json",
"Content-Size": str(os.path.getsize(file_path)),
"Content-Type": "application/octet-stream",
}
files = {'attachment': open(file_path, 'rb')}
filename = os.path.basename(file_path)
api = f"https://dev.azure.com/{organization}/{project}/_apis/wit/attachments?uploadType=Simple&fileName={filename}&api-version=1.0"
resp = requests.post(url=api, files=files, headers=headers, auth=("","*fmhcstt*4nwadqy3uk*go23fga"))
attachment_url = resp.json()['url']
# This part updates an existing work item, adding the attachment here.
api = f"https://dev.azure.com/{organization}/_apis/wit/workitems/{work_item_id}?api-version=6.0"
file_size = os.path.getsize(file_path)
payload = [
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "AttachedFile",
"url": attachment_url,
"attributes": {
"comment": "Test",
"resourceSize": file_size
}
}
}
]
headers = {
'Accept':'application/json',
'dataType': 'application/json-patch+json',
'Content-type':'application/json-patch+json'
}
resp = requests.patch(url=api, headers=headers, json=payload, auth=("","*fmhcstt*4nwadqy3uk*go23fga"))
I found the issue to be with the POST request.
requests.post(url=api, files=files, headers=headers, auth=("","*fmhcstt*4nwadqy3uk*go23fga"))
Should have been:
requests.post(url=api, data=files, ...

PayPal Orders v2: the approveurl of the order ("checkoutnow?token..") returns 302 redirect

I am struggling creating an order with Orders v2 PayPal API.
I have the token, and I do a request with these headers to create the order:
{
"intent": "CAPTURE",
"purchase_units": [{
"description": "Payment",
"amount": {
"value": 'X',
"currency_code": "EUR",
"breakdown": {
"item_total": {
"currency_code": "EUR",
"value": 'X'
},
}
},
"items": [{
"unit_amount": {
"currency_code": "EUR",
"value": 'X'
},
"quantity": "1",
"name": 'item name',
}]
}],
"application_context": {
"brand_name": "My brand name",
"locale": "it-IT",
"return_url": 'my-return-url',
}
}
The order is created and I get the approveurl to let the user to pay.
With the approveurl I do this call:
try {
var response = await http.post(approveurl, body: jsonEncode({"payer_id": payerId}), headers: {
"content-type": "application/json",
'Authorization': 'Bearer ' + accessToken
});
final body = jsonDecode(response.body);
if (response.statusCode == 200) {
return body;
}
return null;
} catch (e) {
rethrow;
}
But I get this reponse:
url = "https://www.sandbox.paypal.com/checkoutnow?token=..."
payerId = "..."
accessToken = "..."
response = {Response}
request = {Request} POST https://www.sandbox.paypal.com/checkoutnow?token=...
statusCode = 302
reasonPhrase = "Found"
contentLength = 61
headers = {_InternalLinkedHashMap} size = 9
0 = {map entry} "paypal-debug-id" -> "95934918777a1"
1 = {map entry} "cache-control" -> "max-age=0, no-cache, no-store, must-revalidate"
2 = {map entry} "location" -> "/webapps/hermes?token=..."
3 = {map entry} "set-cookie" -> "X-PP-SILOVER=name%3DSANDBOX3.WEB.1%26silo_version%3D880%26app%3Dhermesnodeweb%26TIME%3D1595167415%26..."
4 = {map entry} "date" -> "Sun, 19 Jul 2020 14:03:35 GMT"
5 = {map entry} "vary" -> "Accept"
6 = {map entry} "strict-transport-security" -> "max-age=63072000"
7 = {map entry} "content-length" -> "61"
8 = {map entry} "content-type" -> "text/plain; charset=utf-8"
isRedirect = false
persistentConnection = true
And the response.body is:
Found. Redirecting to /webapps/hermes?token=...
With the approvalurl I do this call:
The approval URL is not for you to call. It's a web URL, not an API URL. It's for the paying customer to log in and give their approval of the payment.
However, redirecting them to it would be a bad web experience. For modern web design, you should instead offer an "in context" approval, where your site remains loaded in the background. Here's how to do that: https://developer.paypal.com/demo/checkout/#/pattern/server
With this integration you don't read the approval_url yourself, simply return the Order id when fetched from createOrder.

Can I add headers to httpCall method in envoy lua filter?

I try add more headers to httpCall method, but upstream can't received.
example lua script:
lua
request_handle:httpCall(
"service1",
{
[":method"] = "POST",
[":path"] = "/",
[":authority"] = "lua_cluster",
[":authorization"] = "Basic 123456"
},
"",
1000)
Does it have 3 headers?
You can define any header as below.
request_handle:httpCall(
"service1",
{
[":method"] = "POST",
[":path"] = "/",
[":authority"] = "lua_cluster",
["authorization"] = "Basic 123456",
["any-header"] = "header-value"
},
"",
1000)

Post Json Data using google app script

I am posting a as shown below:
function myFunction() {
var headers = {
};
var jsondata = {
"operator_name": "eee",
"data": [
{
"first_name": "CHaahal"
}
]
};
var payload = JSON.stringify(jsondata);
var url = "http://some_server.com";
var options = {
"method": "POST",
"contentType": "application/json",
"headers": headers,
"payload": payload
};
Logger.log(options);
var response = UrlFetchApp.fetch(url, options);
var responseCode = parseInt(response.getResponseCode());
Logger.log(response);
Logger.log(responseCode);
}
At the server side, I am getting an HTML request instead of json request.
When I hit the same API using Postman with the headers set, the api works. Please suggest

Successful consumption of a Azure Machine Learning API?

Does anyone have good documentation of a successful implementation of the Azure ML studio API in a web app that's not ASP.net? I'd like to run on it with ruby on rails, but I guess I have to figure it out on my own.
It is simply a rest API call. Look at this...
data = {
"Inputs": {
"input1":
{
"ColumnNames": ["YearBuild", "City", "State", "HomeType", "TaxAssesmentYear", "LotSize", "HomeSize", "NumBedrooms"],
"Values": [ [ "0", "Anchorage", "AK ", "Apartment", "0", "0", "0", "0" ], [ "0", "Anchorage", "AK ", "Apartment", "0", "0", "0", "0" ], ]
}, },
"GlobalParameters": {
}
}
body = str.encode(json.dumps(data))
url = 'https://ussouthcentral.services.azureml.net/workspaces/45aeb4d8283d4be6ae211592f5366af5/services/07ffeeb6fcb84f16bc62cdcf67fd95b3/execute?api-version=2.0&details=true'
api_key = 'abc123' # Replace this with the API key for the web service
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib2.Request(url, body, headers)
Give a shot at trying with the postman app in chrome first. Setting your headers, just as above, your data goes in the post payload in the json format.
Here you'll find Ruby code (not python)
data = {
'Inputs' => {
'input1' => [
{
'weekday' => 1,
'hour' => 2,
'events' => 0
}
]
},
'GlobalParameters' => {}
}
body = data.to_json
url = 'https://asiasoutheast.services.azureml.net/subscriptions/[tour stuff...]execute?api-version=2.0&format=swagger'
api_key = '[your api key]'
headers = {'Content-Type': 'application/json', 'Authorization': ('Bearer '+ api_key)}
RestClient::Request.execute(method: :post, url: url, payload: body, headers: headers)

Resources