Using Json in KRL - json

I'm having trouble with parsing my Json, when i place the url in the browser i get this as a return {"token": "7xv6r32eay5n376", "secret": "589bc72ix7mowua"} So all i want to do is get that string and parse out the token and secret and display the values in a notify to confirm i'm getting the correct information. Can anyone see what i'm doing wrong?
rule first_rule {
select when pageview ".*" setting ()
pre{
json=http:get(/* I place my URL here */);
content = json.pick("$..content");
token=content.decode();
tok=token.pick("$..token");
sec=token.pick("$..secret");
message="Token: "+tok+" "+"Secret: "+sec;
}
notify("Values: ",message);
}
}

so i fixed my KRL problem, I guess when using http:get(); you must use double quotes "" not single '' in the get().

Related

Typescript HttpClient.post returning bad request from json formatted string

Ok I have been manipulating this string for hours! So any help is greatly appreciated
I am trying to simply make a post call and generate a password. The api is setup to take in a string a parses the json formatted string itself.
private headers = new HttpHeaders({ 'Content-Type': 'application/json' });
constructor(http: HttpClient) {
var url: string = 'https://eus-safeaccounts-test.azurewebsites.net/' + 'passwords/generate';
var body: string = '"{\"regex\":\"[a-zA-Z0-9]\",\"minLength\":8,\"maxLength\":12}"';
http.post<string>(url, body, { headers: this.headers }).subscribe(result => {
this.signUpResponseStr = result["password"];
}, error => console.error(error));
}
This call returns code 400 bad request. (I think because the text is not being seen as json?)
However, if we set body = '""'; then we get a password sent back from the api no problem. It is seen as an empty string on API side and then they give us a password. Exploring further I tried setting body = '"abc"'; because that is a string not following json format. In this case, we DO NOT get bad request 400, but the api recognizes bad json format and returns Invalid Json
My Question:
What should the body string look like for me to send this request? The API is open so anyone can reproduce and the API code shouldn't have anything to do with the 400 bad request issue, as we can see from my explorations, but the code is here https://github.com/nickpavini/SafeAccountsAPI.
Thanks for any help! :)
EDIT: I also tried sending as JSON type and I also tried JSON.stringify() with no luck
Found it. The string is a bit tricky to understand but hopefully this will help others.
body = '"{\\"regex\\":\\"[a-zA-Z0-9]\\",\\"minLength\\":8,\\"maxLength\\":12}"'
In this case it seems that the body contains a string. (the actual string that will be received by the server)
Inside that string, whenever we need the server to see a " that does not close the string, we must pass an actual backslash \\ and then a ". We do not need 3 backslashes in this case because the single quote ' at the beginning makes sure all paranthesis are included.
Note: Test this with the api in question if it seems weird to you. I think it has to do with the api implementation.
Probably body should not be double quoted, and should look instead like...
var body: string = '{"regex":"[a-zA-Z0-9]","minLength":8,"maxLength":12}'

How to place a multi-line single string JSON in POSTMAN?

Here is what I am using in Python 3:
payload={"query": """query
{
organization(login: "MY-ORG-ID") {
samlIdentityProvider {
externalIdentities(first: 10) {
edges {
node {
user {login}
samlIdentity {nameId}
scimIdentity {username}
}
}
}
}
}
}"""
}
URL = 'https://api.github.com/graphql'
HEADERS = {'accept': 'application/vnd.github.v4.idl', 'authorization': 'bearer MY-GITHUB-TOKEN'}
response = requests.post(url=URL, json=payload, headers=HEADERS)
It just works fine.
However, I am trying to use this query in POSTMAN tool but have no clue how to do this. I tried to remove 3-double quotes """ """, I get Unexpected 'q' error. When I use double quotes instead of 3-double quotes and login: \"MY-ORG-ID\", I get "message": "Problems parsing JSON" error.
There's no problem with headers and URL. I just gave them here for completeness.
If you're trying to enter the query into body of your post request in the postman app, a quick workaround to achieve multiple lines is to use a placeholder in the form of an environment variable in your body and enter the query in your pre-request script:
In your body:
{
"query":{{query}}
}
In your pre-request script:
pm.environment.set("query", JSON.stringify(
`
query {
organization(login: "MY-ORG-ID") {
samlIdentityProvider {
externalIdentities(first: 10) {
edges {
node {
user {login}
samlIdentity {nameId}
scimIdentity {username}
}
}
}
}
}
}
`
));
Note that ` in the above code is a backtick, not a single quote!
It's not the best solution ever, but the only one that worked for me so far in Postman to avoid entering more complex queries/mutations in a single line.
Hope this helps.
Postman has a "graphql" type of request body. It means you can write your query without quotes (see screenshot attached). Also, it is useful when you are assigning variables to query/mutation.
P.S. you might need to update your postman to get a "graphql" type of body payload.
Apparently you can't, therefore you need to turn your multiline string into a single string.
Quickest way to do this is to paste it in a web browser search bar for a format change, then copy and paste from the web browser search bar back into postman.
Triple quotes in Python denote a multi-line string right? So try double quotes, and login: \"MY-ORG-ID\" and placing the entire query in a single line?
{
"query":"query{organization(login: \"MY-ORG-ID\") {samlIdentityProvider {externalIdentities(first: 10) {edges {node {user {login}samlIdentity {nameId}scimIdentity {username}}}}}}}"
}

Modify HTTP Request value in Chrome automatically

Is there a way or an app to always change the value of a POST Request to a specific URL in Chrome?
Try chrome.webRequest. Specifically, chrome.webRequest.onBeforeRequest.addListener
You would provide the string ["blocking"] as an attribute for the opt_extraInfoSpec parameter, and as a return value provide an object of type BlockingResponse which specifies what changes you want to make to the request.
Also, to get the body of the POST request, opt_extraInfoSpec also needs to contain the string "requestBody"
Your code would look something like this:
chrome.webRequest.onBeforeRequest.addListener( function(details){
//
if(details.method == "POST")
var new_url = "http://stackoverflow.com/my_new_url";
return {redirectUrl: new_url};
}, ({urls: ["http://*/*", "https://*/*"] }), ["blocking", "requestBody"]);
Dcoumentation at https://developer.chrome.com/extensions/webRequest
EDIT: The code you would place in the background page only.

Could not parse request body into json: Unexpected character (\'-\' (code 45)) AWS Lambda + API + Postman

I have been trying for a few days to get a parameter sent from the API Gateway in AWS to a Lambda function and I am having no success.
I decided to start from the beginning so I followed their walkthrough (http://docs.aws.amazon.com/apigateway/latest/developerguide/getting-started.html#getting-started-new-lambda)
I have checked this walkthrough twice and I have followed the steps to the letter.
Problem
When I test the API from Postman or in Swift I am getting the error:
{"message": "Could not parse request body into json: Unexpected character (\'-\' (code 45)) in numeric value: expected digit (0-9) to follow minus sign, for valid numeric value\n at [Source: [B#c036d15; line: 1, column: 3]"}
In postman, When I view the result as JSON I just get
Bad String
Lambda Function
The function is the basic example from the Walkthrough:
console.log('Loading event');
exports.handler = function(event, context) {
var name = (event.name === undefined ? 'No-Name' : event.name);
console.log('"Hello":"' + name + '"');
context.done(null, {"Hello":name}); // SUCCESS with message
};
When Tested from the Lambda Console and with the Test data I get the result:
{
"Hello": "TestUser123"
}
When Tested from the API Gateway Test, The result is also:
{
"Hello": "TestUser123"
}
Can anyone see why both test consoles are allowing this work but when tested with POSTMAN or used within a Swift Script it does not work ?
Edit 1
In postman, I have set the content-type to application/json
The script returns the default:
{
"Hello": "user"
}
However, When I add in the parameters name and TestUser123 in POSTMAN, this is when it returns the error.
Update 1
Ok, so I changed the mapping template to one that I found on another answer:
{ "name": "$input.params('name')" }
Now the result is:
{
"Hello": ""
}
Any Ideas why it is not getting the name?
I just got stuck with this today.
your mapping template is:
{ "name": "$input.params('name')" }
AWS uses AWS Velocity templates, which; even though looks like JSON, is different.
if you use
{ "name": $input.params('name') } // notice no quotes
for the mapping template right at the integration request step, then it should work as expected.
Read the error message very carefully, it actually tells you the problem. For example, I got
Could not parse request body into json: Unexpected character (\'\"\' (code 34)): was expecting comma to separate Object entries
So the problem is that I'm missing a comma. I check my Lambda's Integration Request - Body Mapping Template:
{
"age" : $input.json('$.persondata.age'),
"income" : $input.json('$.persondata.income')
"height" : $input.json('$.persondata.height')
}
Can you spot the problem? I am missing a comma after the income line.
Here is another example.
Could not parse request body into json: Unexpected character (\'}\' (code 125)): expected a value
When I look at the Integration Request - Body Mapping Template:
#set($inputRoot = $input.path('$'))
{
"age" : $inputRoot.age,
"height" : $inputRoot.height,
"income" : $inputRootincome
}
Can you spot the problem? I am missing a dot in $inputRootincome.
Error Message :
Could not parse request body into json: Could not parse payload into json: Unrecognized token \' \': was expecting (\'true\', \'false\' or \'null\')
Cause of the error : When string values inside the json are not assigned using double quotations in the aws mapping template the error occurs.
Solution : (Please Note : This example is for application/json type request template)
Actually the solution for the problem is, if you are using a value of type string in json then its value should be assigned inside a ("" - double quotation marks) in the mapping template.
The below shown example has the following attributes :
customerId - string (Please note : this value comes from a query parameter)
customerName - string
customerAge - integer
isPermanentEmployee - boolean
customerAddress - string (Please note this is an optional parameter)
And the mapping template should be defined like the example shown below
Refer the example below :
#set($inputRoot = $input.path('$'))
{
"CustomerId": "$input.params('customerId')",
"CustomerName": "$inputRoot.customerName",
"CustomerAge": $inputRoot.customerAge,
"IsPermanentEmployee": $inputRoot.isPermanentEmployee
"CustomerAddress ": #if($inputRoot.customerAddress == "") "" #elseif($inputRoot.customerAddress != "") "$inputRoot.customerAddress" #end
}
If you note the above mapping template, I would have given string values inside double quotation marks("") which will solve the error
Also this example contains how to handle optional parameters in aws mapping templates using #if#else statements.
It is likely that you had copy-pasted multiple lines in your "Integration Request" in the API gateway.
When copying a line and pasting it below, you might have copied the hidden character '\n' at the end of that line. This is probably causing issues at the lambda function.
Example: Copying the line containing age and pasting it twice and modifying them to have height and income respectively.
#set($inputRoot = $input.path('$'))
{
"age" : $inputRoot.age,
"height": $inputRoot.height,
"income": $inputRoot.income
}
Instead of copy-pasting, just type the line out for height and income.

How can I send a big HTML block in JSON

I need to send a big block of HTML in a Json object like this:
JsonResult jsn = Json(new Dictionary<string, object> { { "success", true },
{ "lastPID", posts[0].ID },
{ "content", "" } });
return jsn;
For some reason I get this error when I put that html block into the content variable: Server cannot set content type after HTTP headers have been sent.
This doesn't happen if I return some random non-html content.
Is there any encoding that I need to do before I can send my big block of html?
What about the client end? How do I get back the data.
Looks like this is your problem (and solution)
If you need to send HTML, why not just send HTML rather than JSON?