Alter response in PostMan - postman

I'm using an open API.
But I am only using a small bit of data from the response the API provides. And as I'm testing using the API with different parameters to see the responses.
I don't want to see the entire API response every time I send the request, I only want to see the data that I'm interested in.
For example :
The response has 3 objects. Status, Features and Data. But I'm only interested in the Data object, I only want to see the Data object when making the request
Is there a way I can print a different Response, using the actual response of the Request?
Tests are run to validate data, and Pre-Request scripts are used to do something before the request, but I haven't found anything that changes the form of the Response.

There is no option to modify body but you can use the amazing visualizer feature in postman:
eg:
Set url and method:
GET : https://reqres.in/api/users?page=2
Add below code in test script:
template = `<table bgcolor="#FFFFFF">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
{{#each response}}
<tr>
<td>{{first_name}}</td>
<td>{{email}}</td>
</tr>
{{/each}}
</table>
`;
// Set visualizer
pm.visualizer.set(template, {
// Pass the response body parsed as JSON as `data`
response: pm.response.json().data
});
Now click visualize:
You can see the visualize will show only first_name and email as a table .
You can use same logic in your case
If you want to print it as json itself then use below code in test script:
template = `
<pre><code>{{response}}</code></pre>
`;
console.log( JSON.stringify(pm.response.json().data, undefined, 2))
// Set visualizer
pm.visualizer.set(template, {
// Pass the response body parsed as JSON as `data`
response: JSON.stringify(pm.response.json().data, undefined, 2)
});
Output:

Related

How to get url for htmx get from an SSE event which itself triggers the hx-get call?

I am using django with django-channels and htmx.
In certain cases, my django views will send an SSE event to a user subscribed to the relevant channel, like a notification for example. Some of those events (depending on event name) needs to trigger a modal pop-up (like a rating modal after an e-commerce order or service completes).
I have implemented the requirements of the server-side event and data generation. I want to use the htmx sse extension on the frontend (django template).
My problem is, I want to get an event, let's say order_complete, and use that to trigger an hx-get call to a particular url which will be sent by the sse event. That hx-get's response will then be placed in the placeholder where modal view logic exists. I can get the event and trigger the get request as described in the htmx sse extension docs, but I don't know how to get the url to put in the hx-get.
I have very little knowledge of JavaScript and not all that much more on htmx. I've looked at out of band swaps but I'm not sure if that's what I need.
I'd appreciate any opinion or suggestions for proceeding including a non-htmx solution if it's better performing or easier.
Thank you.
You can append parameters to a (fixed) url.
In a client side javascript handle the sseMessage event.
document.body.addEventListener('htmx:sseMessage', function (evt) {
//* check if this event is the one you want to use
if (evt.detail.type !== "order_complete") {
return;
}
//* If a JSON string was sent, leave it as it is
//evt.detail.elt.setAttribute("hx-vals", evt.detail.data);
//* if not
var msg = {};
msg.orderId = evt.detail.data;
evt.detail.elt.setAttribute("hx-vals", JSON.stringify(msg));
});
see https://htmx.org/attributes/hx-vals/
resulting url if evt.detail.data was 123:
/orders/showmodal?orderId=123
the html:
<div hx-ext="sse" sse-connect="/sse-something">
<div hx-get="/orders/showmodal"
hx-trigger="sse:order_complete"
hx-swap="innerHTML"
hx-target="#idModalPlaceholder">
</div>
</div>
Update
You can also use an event listener just for order_complete.
document.body.addEventListener('sse:order_complete', function (evt) {
//* If a JSON string was sent, leave it as it is
//evt.detail.elt.setAttribute("hx-vals", evt.detail.data);
//* if not
var msg = {};
msg.orderId = evt.detail.data;
evt.detail.elt.setAttribute("hx-vals", JSON.stringify(msg));
});

POSTMAN - Extract sessionid's value from HTML body response

I'm trying to extract a value from a response to a GET HTTP and storing this value in an environment variable using POSTMAN, then i would use this value for the next HTTP request. This is is an extract of the body response:
<p style="display:none;"><input type="hidden" name="sessionid" id="sessionid" value="e8e63af56d146f42e80f6cd8602cd304708efa58d60e9a43f91cb12e8a2064f4"/><input type="hidden" name="submitbutton" id="submitbutton" value=""/></p>
I need to extract the "value" and then storing it inside an environment variable.
how can i accomplish this using Test scripting in POSTMAN?
thanks
Update:
After receiving help from this community and this link:
https://community.getpostman.com/t/how-to-extract-a-value-attribute-from-an-input-tag-where-the-body-is-a-web-page/1535/2
I was able to do all the stuff, here my code:
var responseHTML = cheerio(pm.response.text());
var variabile = responseHTML.find('[name="sessionid"]').val();
console.log(variabile);
pm.globals.set("session", variabile);
now i can see the sessionid value saved inside the global variable.

Getting checkbox value in flask

I'm trying to poll the state of checkboxes (this is done in JS every three seconds). This solution returns "None" (see code below); Both printouts (with 'args' and with 'form') return "None". I'm expecting True/False, depending on the checkbox's boolean state.
index.html:
{% extends "layout.html" %}
{% block content %}
<div id="results" class="container">{{data_load|safe}}</div>
<input id='testName' type='checkbox' value='Yes' name='testName'>
{% endblock %}
and the relevant flask app snippet:
#app.route('/', methods = ['GET', 'POST'])
def index():
return render_template('index.html', data_load=timertry())
#app.route('/_timertry', methods = ['GET', 'POST'])
def timertry():
print request.args.get('testName')
print request.form.get('testName')
return "some html going into 'results' div.."
The JavaScript polling function (adapted from here):
$(document).ready(function() {
$.ajaxSetup({cache : false});
setInterval(function() {
$('#results').load('/_timertry?' + document.location );
}, 3000); // milliseconds!
});
This should be simple enough, but none of the SO solutions I looked into (e.g., using jquery, adapting the flask/ajax example, etc.) worked.
EDIT: following mark's suggestion (including the javascript) and adding
print request.values in index.html returns (seen on the console in Aptana):
CombinedMultiDict([ImmutableMultiDict([]), ImmutableMultiDict([])])
Clearly, the request seems empty. The post request is logged (when checkbox is pressed) as:
127.0.0.1 - - [03/Oct/2013 00:11:44] "POST /index HTTP/1.1" 200 -
Any ideas here?
Your javascript does the following every three seconds...
$('#results').load('/_timertry?' + document.location);
In other words, you are using the jQuery load() function. The documentation for that function states that this will, in essence, call an HTTP get request to the URL you provide as the parameter (something like /_timertry?http://www.example.org. In other words, a GET request will be called to /timertry?http://www.example.org, which will be handled by Flask's timertry method.
When you have an HTTP form, and you click the "Submit" button, the browser does some magic to push all of the values to the server in the request. When you just do a simple AJAX request, none of that happens for you. Instead, you need to explicitly state what you want to be passed as data to the server (although there are plugins to help you with "post the values of an HTML form using AJAX").
So, because at no point did you do anything in your Javascript to retrieve the value of checkbox to include it into the AJAX request, the AJAX request has no values specifying that the checkbox was checked. You would need to have jQuery check if the box is checked...
var isChecked = $('#testName').is(':checked');
# Now do something with isChecked...
From what I can tell, however, you are sort of misusing HTTP: the load function will make a GET request, and you probably want something to happen as a request of the request. You probably want to make it do a POST request instead (see here and here). Also, you mentioned that you're looking for something to post when a value is changed. Putting this together, you can do something like this...
// Ensure that the function is called when the DOM is ready...
$(function() {
// Register an event that should be fired when the checkbox value is changed
$('#testName').change(function() {
var data = { isChecked : $(this).is(':checked') };
$.post('/', data);
});
})
In this case, we have an event that is called when a checkbox is checked, and that event causes us to make a POST request to the server.
I'm going to answer this question which was found in the comments of the question
"which becomes a question of how to submit a form without a 'submit' button.."
So it is very possible to submit a value when a user clicks on the button
{% block content %}
<form id="target" action="YourViewName">
<div id="results" class="container">{{ data_load|safe }}</div>
<input id='testName' type='checkbox' value='Yes' name='testName'>
</form>
{% endblock %}
$( "#results" ).click(function() {
$( "#target" ).submit();
});
If you want to stay on the same page, however, you're going to need to use an ajax call to pass the data back rather then use a standard submit, however This tutorial covers that topic fairly well. but a basic change to send the data back would look like
$( "#results" ).click(function() {
var request = $.ajax({
type: "POST",
url: "/YourViewName",
data: {'input_value':$('#testName').val()},
dataType: "html"
}).done(function(msg) {
// I don''t know what you want to do with a return value...
// or if you even want a return value
}
});
and the flask would look like
#app.route("/YourViewName")
def example():
list_name = request.args.get("input_value")
#if you don't want to change the web page just give a blank return
return ""

Using django serializer to json while AJAX but using templatetags on response

I have a model table which I am serialized to JSON on an AJAX operation.
Now on the client side I have the model structure as JSON but I would love to use django template tags on the data which has been send.
For example, assume I have a date parameter in my JSON model. django serializer will serialized it and I have no control over it on the client-side because it is already been "compiled".
Is there any way to dosomething like that ?
If you want to format the data first, then send a rendered template fragment as your Ajax response, rather than JSON.
On the client side you can use some javascript based template engine like mustache.
/* For example */
var json_data = {
name: "Joe",
amount: 10.55
};
var template = "{{name}} spends {{amount}}";
$('#some-div').html(Mustache.render(template, json_data));
On django templates it is a pain to escape {{ stuff }} without something like the very handy {% verbatim %} template tag provided by this gist.
Another approach is: use static files as client side templates and fetch them with AJAX calls.

form submit jQuery mobile

I've gotten it into my head that mobile applications don't like form submits the same way html does, so I thought I'd better have a sanity check on Stackoverflow.
For example, instead of having <input type="submit"...>, it looks like I should now use <a data-role="button"...>
Q: Can I continue to use <input type="submit"...> for mobile applications?
The reason why I ask is because the action page has some logic, such as:
<cfif structKeyExists(form,"Save")>
jQuery Mobile, at least as of this writing, by default submits forms via AJAX using the method specified on the form being submitted. POST submissions will still be posted to the server in the background, so ColdFusion will still see the form variables that are passed in as usual. When a response is generated, jQuery Mobile will take the response and transition the view over to whatever HTML was returned. In my own testing you can continue to use a normal submit button as well. If you want a standard submission rather than an AJAX submission, add data-ajax="false" to the form tag.
If you want to programatically submit a form, set the data-ajax attribute for the form to false and then set an event handler for the submit event for the form:
<form data-ajax=false></form>
$(function () {
$('form').bind('submit', function (event) {
event.preventDefault();
$.post('path/to/server.file', $(this).serialize(), function (data) {
alert('Server Response: ' + data);
});
});
});