Validate response in Postman test script - postman

I am inserting data in postman. I want to apply validation from post method in test script. I am new to postman, I am not able to understand.
Here is the JSON.
{
"firstname": "pradeep",
"lastname": "tiwari",
"mobile_no": 9911844349,
"email": "pradeep#gmail.com",
"user_type": 4,
"password": "pradeep1",
"confirmPassword":"pradeep1",
"dob":"nanana",
"u_org":25,
"isfoundingpartner":"undifine",
"gender":1
}

You can use built in snippets for starters to validate your basic response messages. https://learning.getpostman.com/docs/postman/scripts/test_examples/

In order to carry out validation on your responses, you will first need to parse the data into a JavaScript object using below
var jsonData = pm.response.json();
You can use the below code to check for particular values in the response body
pm.test("Verify Json values", function () {
pm.expect(jsonData.firstname).is.to.equal("pradeep");
pm.expect(jsonData.lastname).is.to.equal("tiwari");
pm.expect(jsonData.gender).is.to.equal(1); `
});

Related

API Gateway integration response mapping: parse statusCode and body from Step Function output

I want to parse 'statusCode' and 'body' values from API Gateway integration response using VTL and return those as a method response like this:
Request status: 201
Response body: {"firstName":"He","lastName":"Man","email":"he.man#eternia.com"}
My API Gateway Step Function integration is returning the following integration response body (this is before transformation, non-relevant attributes are removed from output):
{
"output": "{\"statusCode\":201,\"body\":{\"firstName\":\"He\",\"lastName\":\"Man\",\"email\":\"he.man#eternia.com\"}}"
}
I would assume this to work:
#set ($output = $util.parseJson($input.json('$.output')))
#set ($statusCode = $output.statusCode)
#set ($context.responseOverride.status = $statusCode)
$output.body
But status is not updated and body is empty
Request status: 200
Response body: <empty>
With this approach I can parse the body:
#set ($bodyObj = $util.parseJson($input.body))
#set ($output = $util.parseJson($bodyObj.output))
#set ($context.responseOverride.status = $output.statusCode)
$output.body
statusCode is updated but body is returned as object representation i.e. not JSON.
Request status: 201
Response body: {firstName=He, lastName=Man, email=he.man#eternia.com}
How to serialize $output.body correctly to JSON in above case? API Gateway doesn't seem to have $util.toJson function like AppSync does (https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-programming-guide.html)
I've confirmed parsing output-variable works correctly:
#set ($output = $util.parseJson($input.json('$.output')))
$output
Request status: 200
Response body: {"statusCode":201,"body":{"firstName":"He","lastName":"Man","email":"he.man#eternia.com"}}
Relevant reference documentation:
https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartSyncExecution.html#API_StartSyncExecution_ResponseSyntax
https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html
I ran into this exact issue. There indeed does not seem to be a way to convert to JSON directly, so I devised a way to write JSON to the API Gateway response using Apache VTL:
#set ($outputObj = $util.parseJson($input.path('$.output')))
#foreach ( $key in $outputObj.body.keySet() )
"$key": $outputObj.body[$key] #if ($foreach.hasNext),#end
#end
Hope this helps!
(This works for a simple use case like the one you described, but doesn't generalize to nested objects, etc.)
I ran into this same issue. This is how I solved it in the end. The solution provided by #noahtk7 was good for simple object, I have large nested object I needed.
For this to work you need to have your body returned as a base64 encoded string. This is easy to do in a step function. E.G:
"Pass": {
"Type": "Pass",
"Next": "Success",
"Parameters": {
"Base64.$": "States.Base64Encode(States.JsonToString($.Response.Body))"
},
"ResultPath": "$.Response.Body"
}
Then in the api response mapper:
#set($output = $util.parseJson($input.path('$.output')))
#set($context.responseOverride.status = $output.Response.Status)
$util.base64Decode($output.Response.Body.Base64)
Would give me a result of:
{
"foo": "bar",
"Id": "c2b2220c-00e3-4499-87c0-d06ea5e5f1f4"
}

Postman Examples Dynamic Response Based on Request Data

Probably missing something completely obvious in the docs but is it possible to echo request data in a Postman Example / Mock Server response based on the input request.
Example Request:
POST:
{
"firstName": "{{$randomFirstName}}",
"lastName": "{{$randomLastName}}",
"phoneNumber": "{{$randomPhoneNumber}}",
"email": "{{$randomExampleEmail}}",
"employeeId": "{{$randomInt}}"
}
Intended example response:
{
"id": {{$randomInt}},
"firstName": "{{$req.firstName}}",
"lastName": "{{$req.lastName}}",
"phoneNumber": "{{$req.phoneNumber}}",
"email": "{{$req.email}}",
"employeeId": "{{$req.employeeId}}"
}
I see you want to use Postman's dynamic 'faker' variables in the request body to be returned in the mock response. A similar use case is supported for the request URL (refer to the section on 'wildcards' here) but not body.
Here's one way to achieve this with the request body:
Create an environment 'e1' with variable 'firstName'.
Edit your mock to add the environment 'e1'.
Use the same environment variable {{firstName}} in the response body of your example.
Dynamically update the value of 'firstName' before sending the mock request. If you're using the Postman client, you can do this using the pm.environment.set method. If not, then you can use the Postman API to do this.
On the other hand, you can simply use the same faker variable {{$randomFirstVariable}} in your mock example response as well, but the value returned could differ from the one sent in the request.

Telegram bot sendMediaGroup() in Postman - JSON-serialized array?

I'm using Postman app to interact with a Telegram bot api. I've sent photos using the sendPhoto() method, like this:
https://api.telegram.org/botToken/sendPhoto?chat_id=00000000&photo=AgAC***rgehrehrhrn
But I don't understand the sendMediaGroup() method. Can someone post an example how to compose the https string to send two photos?
Thanks
You need to send a POST request at the url https://api.telegram.org/botToken/sendPhoto with a JSON body. You are using the url to specify all the parameters of the request but urls are only 2000 characters long. The body of a POST request, instead, has no limits in terms of size. The JSON body should look something like this:
{
"chat_id": 777000,
"media": [
{
"type": "photo",
"media": "https://example.com/first_photo_url.png",
"caption": "an optional description of the first photo",
"parse_mode": "optional (you can delete this parameter) the parse mode of the caption"
},
{
"type": "photo",
"media": "https://example.com/fsecond_photo_url.png",
"caption": "an optional description of the second photo",
"parse_mode": "optional (you can delete this parameter) the parse mode of the caption"
}
],
}
For more info see:
how to send JSON (raw) data with Postman
and
sendMediaGroup Telegram API's method.
You must send JSON as a string, or serialized JSON, to Telegram API. The format is as same as #GioIacca9's answer.
Note: only the caption in the first image will be showen.
Have a try this Python code.
def send_photos(api_key, chat_id, photo_paths):
params = {
'chat_id': chat_id,
'media': [],
}
for path in photo_paths:
params['media'].append({'type': 'photo', 'media': path})
params['media'] = json.dumps(params['media'])
url = f'https://api.telegram.org/bot{api_key}/sendMediaGroup'
return requests.post(url, data=params)
if __name__ == '__main__':
send_photos('your_key', '#yourchannel', ['http://your.image.one', 'http://your.image.two'])

Postman - Use part of the response data from one test in another test

I require help to execute a postman test which requires a response output from another test. I have checked with various forums but a solution is not available for this particular scenario.
Example
Test 1 response:
{
"items": [
{
"email": "archer+qa01#gmail.com",
"DocumentName": "tc",
"type": "URL",
"url": "https://localhost:8443/user/terms?statusno=a5f2-eq2wd3ee45rrr"
}
]
}
Test 2:
I need to use only the a5f2-eq2wd3ee45rrr part of the response data from Test 1, this can be seen in the url value above. I need to use this value within Test 2
How can I make this work with Postman?
Not completely sure what the response data format is from the question but if it's a simple object with just the url property, you could use something simple like this:
var str = pm.response.json().url
pm.environment.set('value', str.split('=', 2)[1])
This will then set the value you need to a variable, for you to use in the next request using with the {{value}} syntax in a POST request body or by using pm.environment.get('value') in one of the test scripts.
Edit:
If the url property is in an array, you could loop through these and extract the value that way. This would set the variable but if you have more than 1 url property in the array it would set the last one it found.
_.each(pm.response.json(), (arrItem) => {
pm.environment.set('value', arrItem[0].url.split('=', 2)[1])
})
If you get JSON response and then send JSON in body, I would do the following:
1) In test script(javascript):
var JsonBody = pm.response.json();
var strToParse = JsonBody.url;
var value = strToParse.slice(indexOf("?status=")+"?status=".length);//parse string
//manually but you can google for a better solutions.
pm.environment.get("varName" , value)
2) You can use it! In scripts like: pm.environment.get("varName"), and everywhere else using {{varName}}

Send Json via $.load() of jQuery in a GET request to Django

Happy coding weekend to everyone!!!.
I'm stuck trying to send a JSON object via $.load() of jQuery, i want to send it with the GET method, this is the code that i have in my javascript code, I attached the Ajax request that receives the JSON Object for clarity:
function ajaxLoadClasses() {
$.ajax({
url: 'load_classes/',
type: 'GET',
dataType: 'json',
success: function(json) {
$.each(json, function(iterator,item) {
loadViaGet(item);
});
},
error: function(xhr, status) {
alert('Sorry, there was a problem!');
},
complete: function(xhr, status) {},
});
}
function loadViaGet(item) {
$div = $('div.myClass');
//Here is where I'm stuck, I'm not sure if this is the way to send the JSON obj
$div.load('thisAppURL/?json=' + encodeURIComponent(item), function() {
alert('Load was performed');
});
}
The "item" json obj received was made out of a Model of Django using
jsonToSendToAjax = serializers.serialize('json', obj)
And I don't think that I'm using the correct methods in my Django to deserialize the JSON object or to convert the JSON object into a Python object so I can handle it in my view and send it to a template:
def popUpForm(request):
jsonData = request.GET['json']
deser = serializers.deserialize('json', jsonData)
#This could be another way to convert the JSON object to a Python Object
#pythonObj = simplejson.loads(jsonData)
return render_to_response('class_pop_up_form.html', deser)
It will be very helpful if someone can help me with this!! I'm really struggling with it but I don't find the right way to do it.
EDIT 1 :
I want to send the JSON object via the GET with the $.load() function, not with the POST method,as I read in the jQuery api: http://api.jquery.com/load/ the $.load() method works as follow: .load( url, [data], [complete(responseText, textStatus, XMLHttpRequest)] )
The POST method is used if data is provided as an object; otherwise, GET is assumed.
EDIT 2:
Forget about sending the json object via the GET method, now I'm using the POST method, but now I don't figure out how to use that json object in my Django View.py, don't know if i need to deserialize it or not, the format of the json object that I'm using is the following:
{"pk": 1,
"model": "skedified.class",
"fields": {
"hr_three": null,
"group": 1,
"name": "Abastecimiento de agua",
"day_three": null,
"day_one": "1 , 3",
"hr_one": "10+/3",
"online_class": null,
"teacher_name": "Enrique C\\u00e1zares Rivera / ",
"day_two": null,
"class_key": "CV3009",
"hr_two": null }
}
This isn't how jQuery suggests you should send the data and it's probably not a good idea to do it this way either. Your url gets very ugly and long very quick if you add the json string to it like that.
Use the second argument for $.load; "data" (see http://api.jquery.com/load/) instead. So something like
$div.load('thisAppURL', {"json": encodeURIComponent(item)});
Also, if you want to trace the output, I'd sugest using the third argument, the callback function, and use console instead of alert. You can get the actual return from the server that way too. So you'd get something like:
$div.load(
'thisAppURL',
{"json": encodeURIComponent(item)},
function(response, status, xhr){
console.log(response);
}
);
the question was not clear to me but you can send json via load as the second argument
$div = $('div.myClass');
//Here is where I'm stuck, I'm not sure if this is the way to send the JSON obj
$div.load('thisAppURL/?json=' + encodeURIComponent(item),{"name":"john","age":"20"}, function() {
alert('Load was performed');
});
for converting javascript array to json see this answer Convert array to JSON
and for deserializing json in django Django Deserialization