Put not working using Poster - json

I am most likely doing something wrong but not sure what. I am trying to test a NetSuite Restlet (web service) using FF poster. I can use Get to work by passing data in the URL. However, I get an error using the Put method.
{"error" : {"code" : "SYNTAX_ERROR", "message" : "SyntaxError: Empty JSON string (null$lib#3)."}}
It's hitting my catch block below. I read that to create or update we should use Put so not sure why Get works but not Put?
function CreateRecord(jsonobject)
{
try
{
nlapiLogExecution('DEBUG', ' in get = ');
var jsonString = JSON.stringify(jsonobject)
nlapiLogExecution('ERROR', 'JSON', jsonString);
// Mandatory
var name = jsonobject["name"];
nlapiLogExecution('DEBUG', ' name = ', name);
var record = nlapiCreateRecord('customrecordtest');
record.setFieldValue('name', name);
var id = nlapiSubmitRecord(record, true);
nlapiLogExecution('DEBUG', 'id = ', id);
return jsonobject;
}
catch (err)
{
nlapiLogExecution('ERROR', 'Error', err.message);
return err.message;
}
}
Poster:
https://rest.sandbox.netsuite.com/app/site/hosting/restlet.nl?script=351&deploy=1&name=Restlet Test

A PUT request will not look for data in the URL. It will look for JSON in the body of the request itself. So instead of &name=Restlet Test, you will need to send an object in the body of the request like { "name" : "Restlet Test" }

Related

How to use postman to test the call of my api

i am currently building an frontend app to display a generated qr code from an api. I started to implement the code but got a problem with the parsing of the response
here is the frontend code with the call
<template>
<div>
<p>test</p>
</div>
</template>
<script>
// Configuration
let myConfiguration = {
"Account" : "CH4431999123000889012",
"CreditorName" : "Muster AG",
"CreditorAddress1" : "Hauptstrasse 1",
"CreditorAddress2" : "8000 Zürich",
"CreditorCountryCode" : "CH",
"DebtorName" : "LivingTech GmbH",
"DebtorAddress1" : "Dörflistrasse 10",
"DebtorAddress2" : "8057 Zürich",
"DebtorCountryCode" : "CH",
"Amount" : "1.50",
"ReferenceNr" : "21000000000313947143000901",
"UnstructuredMessage" : "Mitteilung zur Rechnung",
"Currency" : "CHF",
"QrOnly" : "false",
"Format" : "PDF",
"Language" : "DE"
}
// Call function to create invoice
let myFile = generateQrInvoice(myConfiguration);
// Work with binary data
if(myFile != null) {
// ...
}
function generateQrInvoice(myRequestConfiguration) {
// Main configuration
let myEndpointUrl = "http://qrbillservice.livingtech.ch";
let myEndpointPath = "/api/qrinvoice/create/";
let myApiKey = "(falseApiKey)";
// GET parameters
let myGetParams = new URLSearchParams(myRequestConfiguration);
// Perform request
fetch(myEndpointUrl + myEndpointPath + "?" + myGetParams, {
method: "GET",
mode: "cors",
cache: "no-cache",
headers: {
"APIKEY": myApiKey,
"Accept": "application/json"
}
}).then(function (myResponse) {
try {
// Check status
if(myResponse.status == 200) {
// Read and parse JSON
let myJsonObject = JSON.parse(myResponse);
// Check if error
if(myJsonObject["isSuccessed"] == "true") {
if("base64Content" in myJsonObject && myJsonObject["base64Content"].trim() != "") {
// E.g. send file to client
let myBlob = new Blob(atob(myJsonObject["base64Content"]), {type: "application/pdf"});
let myBlobUrl = URL.createObjectURL(myBlob);
window.open(myBlobUrl);
// Return data
return atob(myJsonObject["base64Content"]);
} else {
throw "no data provided";
}
} else {
throw myJsonObject["message"];
}
} else {
throw "status code " . myResponse.status;
}
}
catch(e) {
// Handle exception
console.warn("Error: " + e.message, e);
return null;
}
}).catch(function (err) {
// Handle exception
console.warn("Error: " + err.message, err);
return null;
});
}
</script>
and here is the response i get when i inspect on the browser :
Error: Unexpected token 'o', "[object Response]" is not valid JSON SyntaxError: Unexpected token 'o', "[object Response]" is not valid JSON
at JSON.parse (<anonymous>)
at app.vue:61:42
I didn't write the apikey here but it is written on my code.
As it has been a long time since i didn't code like this, i don't really see yet how to tackle the problem. I tried to test with postman but it appears my request is not good yet.
If someone has an idea, i would be very happy to learn.
Thank you very much in advance,
Eugene
So i test myResponse and it is a JSON.
However the problem remains : i saw in the console that the api answers successfully api response
So i figured that i could just replace
let myJsonObject = JSON.parse(myResponse)
by
let myJsonObject = myResponse
and try to see what goes.
Now it goes directly in the catch(e) and send me an error response.
It looks like in my code, i don't go in the right direction to use the information i got from the api.
Here is partially the information i got : {"isSuccessed":true,"statusCode":200,"mimeType":"application/pdf","message":"QrBill is successfully generated","isQrOnly":false,"errors":"null","base64Content":(here is the content, i didn't added because it is quite long)}
my question therefore is how could recover the pdf and show it to the end user?

How to access JSON?

I am wrote API method, after calling that method , I got my response like
[
{
"spark_version": "7.6.x-scala2.12"
}
]
Now I want to have variable in my API method which store value 7.6.x-scala2.12.
API Controller method
[HttpGet]
public IActionResult GetTest(int ActivityId)
{
string StoredJson = "exec sp_GetJobJSONTest " +
"#ActivityId = " + ActivityId ;
var result = _context.Test.FromSqlRaw(StoredJson);
return Ok(result);
}
So how this variable should call on this response to get string stored in spark_version?
Thank you
As you have the JavaScript tag, here's how you'd do it in JS:
If you are able to call your API method, then you can just assign the response to a variable. For example, if you are calling it using the fetch API, it would look something like:
let apiResponse;
fetch('myApiUrl.com').then((response) => {
if (response.status === 200) {
apiResponse = response.body;
console.log('Response:', apiResponse[0]['spark_version']);
}
});
(I defined the variable outside the then to make it globally accessible)

Get random wiki page from cloud functions

I tried to get a random Wikipedia page over their API via Google Cloud Functions. The Wikipedia API works fine. This is my request:
https://de.wikipedia.org/w/api.php?action=query&format=json&generator=random
For testing you can change the format to jsonfm in see the result in the browser. Click here 👍.
But it seems that my functions get destroyed even before the request was completely successfully. If I want to parse the data (or even if I want to log that data) I got a
SyntaxError: Unexpected end of json
The log look like (for example) that (no I haven't cut it by myself):
DATA: ue||"},"query":{"pages":{"2855038":{"pageid":2855038,"ns":0,"title":"Thomas Fischer
Of course, that is not a valid json and can't be parsed. Whatever this is my function:
exports.randomWikiPage = function getRandomWikiPage (req, res) {
const httpsOptions = {
host: "de.wikipedia.org",
path: "/w/api.php?action=query&format=json&generator=random"
};
const https = require('https');
https.request(httpsOptions, function(httpsRes) {
console.log('STATUS: ' + httpsRes.statusCode)
console.log('HEADERS: ' + JSON.stringify(httpsRes.headers))
httpsRes.setEncoding('utf8')
httpsRes.on('data', function (data) {
console.log("DATA: " + data)
const wikiResponse = JSON.parse(data);
const title = wikiResponse.query.title
res.status(200).json({"title": title})
});
}).end();
};
I've already tried to return something here. Like that video explained. But as I look into the node docs https.request don't return a Promise. So return that is wrong. I've also tried to extract the on('data', callback) into it's own function so that I can return the callback. But I haven't a success with that either.
How have to look my function that it return my expected:
{"title": "A random Wikipedia Page title"}
?
I believe your json comes through as a stream in chunks. You're attempting to parse the first data chunk that comes back. Try something like:
https.request(httpsOptions, function(httpsRes) {
console.log('STATUS: ' + httpsRes.statusCode)
console.log('HEADERS: ' + JSON.stringify(httpsRes.headers))
httpsRes.setEncoding('utf8')
let wikiResponseData = '';
httpsRes.on('data', function (data) {
wikiResponseData += data;
});
httpRes.on('end', function() {
const wikiResponse = JSON.parse(wikiResponseData)
const title = wikiResponse.query.title
res.status(200).json({"title": title})
})
}).end();
};

Parsing JSON object sent through AJAX in Django

This is my code creating a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
itemCode : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now the json object looks like:
[{"itemcode":"code1","itemquantity":"quantity1"},{"itemcode":"code2","itemquantity":"quantity2"},...]
My question is how do I parse this data in Django view?
Following is my AJAX function for reference:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: JSON.stringify(items),
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Since I'm sending multiple AJAX request to the same view, I need the 'calltype' data as well.
Thanks you on your answer!! BTW, I badly need to know this simple stuff, which I'm missing
This is my code snippet for parsing:
if (calltype == 'save'):
response_data = {}
bill_data = json.loads(request.POST.get('bill_details'))
itemcode1=bill_details[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
The error being raised is
string indices must be integers
Request your help
For your reference, this is my POST response (taken from traceback):
bill_details = '[{"itemCode":"sav","itemQuantity":"4"}]'
calltype = 'save'
csrfmiddlewaretoken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
EDITED Django View
This is my edited view:
if (calltype == 'save'):
bill_detail = request.POST.get('bill_details')
response_data = {}
bill_data = json.loads(bill_detail)
itemcode1=bill_data[0]['itemCode']
#this part is just for checking
response_data['name'] = itemcode1
jsondata = json.dumps(response_data)
return HttpResponse(jsondata)
I fail to understand the problem. SO, to solve it, my question: what is the datatype of the return for get call and what should be the input datatype for json.loads. Bcoz the error being shown is json.loads file has to be string type!! (Seriously in limbo)
Error:
the JSON object must be str, not 'NoneType'

JSON returning with "\" (Lambda)

I am using AWS Lambda to get JSON from the open weather api and return it.
Here is my code:
var http = require('http');
exports.handler = function(event, context) {
var url = "http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=b1b15e88fa797225412429c1c50c122a";
http.get(url, function(res) {
// Continuously update stream with data
var body = '';
res.on('data', function(d) {
body += d;
});
res.on('end', function() {
context.succeed(body);
});
res.on('error', function(e) {
context.fail("Got error: " + e.message);
});
});
}
It works and returns the JSON, but it is adding backslashes before every " like so:
"{\"coord\":{\"lon\":145.77,\"lat\":-16.92},\"weather\":[{\"id\":803,\"main\":\"Clouds\",\"description\":\"broken clouds\",\"icon\":\"04d\"}],\"base\":\"cmc stations\",\"main\":{\"temp\":303.15,\"pressure\":1008,\"humidity\":74,\"temp_min\":303.15,\"temp_max\":303.15},\"wind\":{\"speed\":3.1,\"deg\":320},\"clouds\":{\"all\":75},\"dt\":1458518400,\"sys\":{\"type\":1,\"id\":8166,\"message\":0.0025,\"country\":\"AU\",\"sunrise\":1458505258,\"sunset\":1458548812},\"id\":2172797,\"name\":\"Cairns\",\"cod\":200}"
This is stopping my over service using (SwiftJSON) detecting this as valid JSON.
Can anyone tell me how to make the API information come out as correctly formatted JSON?
I tried .replace like so:
res.on('end', function() {
result = body.replace('\\', '');
context.succeed(result);
});
It did not change anything. Still had the same output.
You're posting it as a string.
Try context.succeed(JSON.parse(result))
From the docs
The result provided must be JSON.stringify compatible. If AWS Lambda fails to stringify or encounters another error, an unhandled exception is thrown, with the X-Amz-Function-Error response header set to Unhandled.
http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-context.html
So essentially it's taking your json string as a string and calling JSON.stringify on it...thus escaping all the quotes as you're seeing. Pass the parsed JSON object to succeed and it should not have this issue
In case of Java, just return a JSONObject. Looks like when returning string it is trying to do some transformation and ends up escaping all the quotes.
If using Java, the response can be a user defined object as below
class Handler implements RequestHandler<SQSEvent, CustomObject> {
public CustomObject handleRequest(SQSEvent event, Context context) {
return new CustomObject();
}
}
Sample code can be found here.
Do this on your result: response.json()
You can use:
res.on('end', function() {
context.succeed(body.replace(/\\/g, '') );
To replace \ with nothing..