How to parse a JSON response to build additional Paw request? - json

https://paw.cloud/
I have the following JSON coming back from a different API end point:
[
{
"id": 1,
"name": "BigCartel",
"slug": "bigcartel",
"logo_cdn_url": "http://placehold.it/200x200",
"active": true,
"authentication_type": {
"description": "Oauth Authentication Token",
"slug": "oauthauthenticationtoken"
}
},
{
"id": 2,
"name": "Lightspeed Retail",
"slug": "lightspeed_retail",
"logo_cdn_url": "http://placehold.it/200x200",
"active": true,
"authentication_type": {
"description": "Oauth Authentication Token",
"slug": "oauthauthenticationtoken"
}
}
]
I would like to parse this JSON and use it in another section of the paws application. Has anyone found any examples like this? I was trying the custom JS text but that appears to be a dead end.

Solution 1: jq
According to their website, "jq is a lightweight and flexible command-line JSON processor". And you can do jq queries in Paw. We will use it to automatically extract the ID of the field from your latest response.
On the URL field (where you want to have this "smart ID"), right-click and pick "jq JSON processor".
In the "JQ args" field, enter the query (see jq tutorial for details on how this works):
.[] | select(.slug == "bigcartel") | .id
In the JSON input field, right-click and pick Response > Response Raw Body. A popover will open, point the "Request" field to the request from which you want to extract the response body from (your "list" request). This will automatically fetch the body of the latest response of this request.
All done! You should now have this setup:
Solution 2: JavaScript Snippet
Paw exposes JavaScript bindings to write extensions (e.g. jq dynamic value used above is written as an extension). It can also be used to embed little code snippets inline a request. It's helpful to achieve more advanced setups.
Right-click on the URL field where you need to insert your ID. Pick Extensions > JS Script. In the popover, paste this code:
function evaluate(context){
var request = context.getRequestByName("List");
var httpExchange = request.getLastExchange();
var body = JSON.parse(httpExchange.responseBody);
for (var i = 0; i < body.length; i++) {
var member = body[i];
if (member.slug == "bigcartel") {
return member.id;
}
}
return null;
};
You can find the docs of this JavaScript API that Paw exposes in the Paw documentation under the "API Reference" section at the bottom.

Related

Postman: POST request of nested JSON via form-data not working (while via raw-data ok)

I want to POST the following JSON-object via Postman:
{
"title": "test_title",
"date": "2021-12-31",
"attachments": [
{
"name": "test_attachment"
}
]
}
This works perfectly fine, when using Postman's raw input form for the request-body: I get a "201 Created"-response back.
However, when using the form-data to POST the data, I get the error "Invalid data. Expected a dictionary, but got str." (see also screenshot below) What am I doing wrong here? I tried all kind of other versions to enter the attachment-key:value pair but nothing worked so far
I managed to make it work! (note: I added some additional fields compared to the screenshot in question. See below for details:
You did nothing wrong.
If you want to make a request with json object, then you go with raw type (json) in postman.
If you want to upload file, then you use form-data
One more thing, status 201 means the request is succeed, your object has been created.
var express = require('express')
const multer = require('multer')
const upload = multer()
var app = express()
app.use(express.json());
app.post('/test',upload.none(), function (req, res, next) {
res.send(req.body)
})
app.listen(80, function () {
console.log('web server listening on port 80')
})
Above is a sample endpoint which works with both form-data and json , just do a post to http://localhost:80/test with both form data and raw json
you can see both will get parsed correclty
APIs are just abstraction , its like a function that takes in many attribute, how you parse it depends on the implementation ( how the api function is written) .
so answer is "Talk to the developer" on how the API is implemented and what it is supporting
I'm having issue in placing json into form format the way Daniel did in Postman. Need help in figuring out what is it required to place the cascaded json objects into form data format. Please see here that I'm trying to accomplish.
JSON Format (to be filled into Postman form-data section:
{
"primary_object": {
"child_object_1": [{"id": 12345678, "value": "abc"},{"id": 87654321, "value": "xyz"}],
"child_object_2": [
"first_val",
"second_val"
]
}
}

Send an already existing json file as embed using discord.py

I'm working on my first python discord bot and it's turning out to be pretty decent but I wanted to use embeds for certain responses. One of them includes sending all the features of the bots which uses many embeds. I don't have any experience about Javascript or JSON so I used a website "https://discohook.org/" to create an embed as it's GUI based. But as a result, I only get the JSON file and I couldn't find a way where I could load a JSON file and send it as an embed.
The JSON file looks something like this -
{
"content": "Bot Name",
"embeds": [
{
"description": "This command lists all the possible commands which can be used to interact with the bot.",
"author": {
"name": "Help",
"icon_url": "http://4.bp.blogspot.com/-wuUbc-OPOt4/T3ioPh2pAAI/AAAAAAAAAdM/BFFvS5fxVMY/w1200-h630-p-k-no-nu/Questionmark.jpg"
}
},
{
"description": "Bot blesses you. ",
"author": {
"name": "Bless ",
"icon_url": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fwallpapercave.com%2Fwp%2Fwp4775695.jpg&f=1&nofb=1"
}
},
{
"description": "Set status as idle",
"color": 16777215,
"author": {
"name": "Go Sleep",
"icon_url": "https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fmedia.forgecdn.net%2Favatars%2F170%2F652%2F636723641550179947.png&f=1&nofb=1"
}
}
]
You could probably just load the individual variables.
with open(“JSON_FILE.txt”) as json_file:
data = json.load(json_file)
data = data[“embeds”]
Then you can have some way to get the specific dictionary.
for embed in data:
pass
Then just have data defined as the dictionary you want to use.
embed = discord.Embed(description = data[“description”])
embed.set_author(name = data[“author”][“name”], icon_url = data[“author”][“icon_url”]
Maybe it've been a long time, but I have exactly the same problem and I found my own solution. Here it is:
from json import loads
from discord import Embed
# Just for our convinience let's make a function
def parse_embed_json(json_file):
embeds_json = loads(json_file)['embeds']
for embed_json in embeds_json:
embed = Embed().from_dict(embed_json)
yield embed
# And the main code looks like this
with open("bot/embeds/temp_ban_embeds.json", "r") as file:
temp_ban_embeds = parse_embed_json(file.read())
for embed in temp_ban_embeds:
await ctx.send(embed=embed)
So I found a special method from_dict. And it seems like it works with dicts we can get from json.loads method. So you can find the documentation here.

Is there any documentation for EasyPost that shows the raw JSON for the requests, including headers? Or e.g. a PostMan collection?

I'm just doing the preparation for an integration with EasyPost's Shipping API, which will be server side C#, but we always build a PostMan collection for new integrations, so that we can test data separately from the application if there's an issue.
While I do love the fact that EP provide C# libraries and examples, I'm struggling to find anything that just gives me a list of required headers and the raw JSON format for the body of any requests. It feels a bit like they're just being a little too helpful.
I'll be looking at the Orders endpoint probably.
I've got an account, I've checked all their documentation and searched the internet but haven't found anything so I'm hoping I'm not the first developer to want to use a client application for testing outside my code.
Update:
EasyPost now does have a public workspace https://www.postman.com/easypost-api
with at least 1 public collection
The curl examples are basically the same as json:
For the Address creation example:
-d "address[street1]=417 MONTGOMERY ST"
is the equivalent of
{ "address": { "street1": "417 MONTGOMERY ST" } }
(you might have to escape some characters to be valid json).
Check out How to stimulate cURL request to a request using postman for postman with HTTP Basic Auth.
EasyPost does not provide a public Postman collection; however, here is an example of a shipment Postman body (raw) that could be used. You can adjust the values, actions, objects, etc to your needs.
Using the following, you shouldn't need to pass any headers. You'll pass your API key under the username field with the Basic Auth authorization type.
{
"shipment": {
"to_address": {
"id": "adr_123..."
},
"from_address": {
"id": "adr_123..."
},
"parcel": {
"id": "prcl_123..."
},
"carrier_accounts": {
"id": "ca_123..."
},
"options": {
"address_validation_level": "0"
}
},
"format": "json",
"controller": "shipments",
"action": "create"
}

freeradius 3.0.17 rlm_rest parsing json response

I'm trying to authenticate RADIUS Requests against a RESTful API (provided by Customer) using rlm_rest.
The problem I am facing is that
response JSON format (of REST API provided by Customer), is different from rlm_rest default format (indicated in etc/raddb/mods-enabled/rest).
My Virtual Server configuration as below:
Default
authorize {
...
...
rest
if (ok) {
update control {
Auth-Type := rest
}
}
}
mods-enabled/rest
authorize {
uri = "https://3rd-party-API/auth"
method = 'post'
body = 'json'
chunk = 0
tls = ${..tls}
data = '{
"code": 1,
"identifier": %I,
"avps": {
"User-Name": ["%{User-Name}"],
"NAS-IP-Address": ["%{NAS-IP-Address}"],
"Called-Station-Id": ["%{Called-Station-Id}"],
"Calling-Station-Id": ["%{Calling-Station-Id}"],
"NAS-Identifier": ["%{NAS-Identifier}"]
}
}'
}
Result
/sbin/radiusd -Xxx
HTTP response code
200
JSON Body
{
"code": "2",
"identifier": "91",
"avps": {
"Customer-Attributes": "Hello"
...
...
"Acct-Interim-Interval": "300"
}
}
The JSON structure is different from the example, and xlat parse
"code"
"identifier"
"avps"
And, of course, xlat finds no attributes match with the dictionary, while it cannot find "avps" and won't dig deeper.
So I was wondering is there anyway to either
Define the response JSON structure for xlat to parsing
Insert a "is_json" or "do_xlat" flag into the JSON ("avps"), and hope xlat will then dig deeper
Save the JSON and parse with exec/rlm_exec (using JQ or any other bash/JSON tools)
Please advise if there is any workaround. Thanks!
In FreeRADIUS version 4, there's a rlm_json module, which implements a custom node query language based on xpath (jpath), it is extremely limited and only supports some very basic queries (feel free to enhance it via PR :) ).
Below is an example I pulled out of my library of customer configurations. You can see here it's pulling out two keys (externalID and macAddress) from the root level of the JSON doc and assigning them to a couple of custom attributes (Subscriber-ID and Provisioned-MAC).
map json "%{rest_api:https://${modules.rest[rest_api].server}/admin/api/${modules.rest[rest_api].api_key}/external/getDeviceBySerialNumber?certificateSerialNumber=%{lpad:&TLS-Client-Cert-Serial 40 0}}" {
&Subscriber-ID := '$.externalId'
&Provisioned-MAC := '$.macAddress'
}
The xlat expansion can also be modified to send HTTP body data. Just put a space after the URL and pass your custom JSON blob.

How to escape \r\n in the body of a POST in JMeter

I have a JSON response as follows,
{
"name":"John Smith",
"address": "#123\r\nRenault Road\r\n123456\r\n"
}
and I need to extract the address and put it into my next POST request. I use the JSON Extractor as a post processing element and with $..address I set the extracted address to the variable address.
In my next request, I use the following as the POST data,
{
"id": "123456",
"address": "${address}"
}
So when I make the request I see the POST data as,
{
"id": "123456",
"address": "#123
Renault Road
123456
"
}
This breaks at my backend and nevertheless this payload is not identified as a valid JSON as well.
I want to make the request so that the POST data is as follow,
{
"id": "123456",
"address": "#123\r\nRenault Road\r\n123456\r\n"
}
Any help to get this done is highly appreciated.
If you really need to send these line breaks as \r\n you can use some scripting to convert them back.
Add Beanshell PreProcessor as a child of the "next request" HTTP Request Sampler
Put the following code into the PreProcessor's "Script" area:
address = vars.get("address");
address = address.replaceAll("\\r\\n","\\\\r\\\\n");
vars.put("address", address);
The above script will convert line breaks to the textual representation.
References:
vars is a shorthand for JMeterVariables class instance, it provides read/write access to all JMeter Variables
String.replaceAll() - is the method of String class which comes out of box with Java SDK
How to Use BeanShell: JMeter's Favorite Built-in Component - guide demonstrating how to use Java and JMeter APIs using Beanshell test elements to enhance your JMeter tests with scripting if required