How to perform PUT operation to update an API in Jmeter? - json

Below code is for POST API:
{
"request": {
"method": "GET",
"urlPattern": "/identity/v2/users/7983739"
},
"response": {
"status": 200,
"headers": {
"Content-Type": "application/json"
},
"body" : "{ 'language': 'en‐US', 'phoneNumbers': [{'type': 'home','value': 8059662323}, {'type': 'office','value': 8053088006},{'type': 'mobile','value': 6502229400}],'addresses': [{‘address1': '419 State St’,’address2': '2nd Floor’,’city': 'Santa Barbara’,’state': ‘CA’,’postalCode': 93101,’country': ‘US’,’type': ‘shipping'}] }"
}
}
Now, I want to update the body with the below data:
"body" : "{'language':'en‐US','phoneNumbers':[{'type':'home','value':8059662323},{'type':'home','value':6502229400}],'addresses':[{'address1':'419 State St','address2':'2nd Floor','city':'Santa Barbara','state':'CA','postalCode':93101,'country':'US''type':'shipping'}]}"
Can someone tell me how to do it using Jmeter...

Here are the steps:
Add HTTP Request Sampler to your Test Plan
Configure host, port, URL, etc.
Select "PUT" from "Method" dropdown
Switch from "Parameters" to "Body Data" section
Provide new JSON value there
You might also need to add HTTP Header Manager to send at least Content-Type header with the value of application/json.
See Testing SOAP/REST Web Services Using JMeter article for detailed information on how to get started with API testing using JMeter

you can have the entire body in a variable and then user it here with ${variable}
you can also check here http://fabiouechi.blogspot.com/2011/03/jmeter-posting-json-data-to-web-service.html

Related

Cypress intercept API JSON response and extract URL

My web app sends an API POST request to create an application and returns JSON response. I want to access one particular JSON object from that response.
My JSON starts like this
[
{
"status_code": 201,
"body": {
"created": "2021-01-28T00:00:00Z",
"modified": "2021-01-28T00:00:00Z",
"id": "a2d86d17-9b3c-4c4d-ac49-5b9d8f6d6f8f",
"applicant": {
"id": "07f1e1d3-0521-401b-813e-3f777f2673c6",
"status": "Pending",
"first_name": "",
"last_name": "",
"URL": "some onboarding url"
And I wanna take that URL in the JSON response and visit it later in my cypress automation script.
Notice that the JSON repsonse starts with a square bracket not a curly bracket, which means, the whole response is an object, I assume?
My cypress script looks like this
cy.contains('button', 'CONTINUE').click()
cy.EmailGen('candidate').then(email => {
cy.get('#emails\\[0\\]').type(`${email}`)
cy.wrap(email).as('candidateEmail')
})
//writing intercept here, before the Send application button, which triggers the POST req.
cy.intercept('/hr/v1/applications/invite').as('getURL')
cy.get('button').contains('SEND APPLICATION').click({ force: true })
//waiting on the alias of intercept and using interception to print objects from response
cy.wait('#getURL').then((interception)=> {
cy.log(interception.response.body.applicant.URL)
})
cy.Logout()
The script executes with no errors. Just that nothing is logged in the cy.log statement. Below is the screen.
I also tried using another method as given below.
cy.intercept('/hr/v1/applications/invite',(req) => {
req.reply((res=> {
expect(res.status_code).to.equal('201')
expect(res.body.applicant.status).to.equal('Pending')
}))
})
In this case, I get a assert error embedded with the request and response along with some other stuff which I am unable to understand.
The complete error goes something like this...
"expected The following error originated from your test code, not from Cypress.\n\n > A response callback passed to req.reply() threw an error while intercepting a response:\n\nexpected undefined to equal '201'\n\nRoute: {\n "matchUrlAgainstPath": true,\n "url": "/hr/v1/applications/invite"\n}\n\nIntercepted request:{} Intercepted response: {} When Cypress detects uncaught errors originating from your test code it will automatically fail the current test. to include window.zE is not a function"
Its a bit weird to read this..
My application sometimes throws this exception, which I have handled using following code.
cy.on('uncaught:exception', (err, runnable) => {
expect(err.message).to.include('window.zE is not a function')
done()
return false
})
I really hope I have explained everything here. Please, help a noob.
Regards
As Richard Matsen suggested in the comments,
I used console.log(interception.response) and checked the console output in the browser controlled by Cypress.
I Noticed that the response json structure was something different than what I got in the network tab of developers tools, while using the web app.
The response was something like below...
{headers: {…}, url: "https://example.com/hr/v1/applications/invite/batch/", method: null, httpVersion: "1.1", statusCode: 200, …}
body: Array(1)
0:
body:
applicant: {id: "c6b2d686-d4f3-483e-abc8-e4641c365845", status: "Pending", first_name: "", last_name: "", email: "qa2+candidate879#example.com", …}
applicant_status: "NONE"
applicant_status_label: "None"
created: "2021-01-29T00:00:00Z"
get_applicant_status_display: "None"
id: "ad2939f5-c8ab-490a-a9e1-b0474de69e2c"
URL: "some url"
This made me modify the json traverse to
interception.response.body[0].body.applicant.URL
If others have a neat way to handle this, please let me know!

How to determine why an Azure Function App is not triggered by a webhook

I have:
An JavaScript Azure Function in an HTTP webhook configuration; the Function provides a URL; the Function performs an action
A webhook configured in the software I hope to receive notifications from
An Azure Logic App with an HTTP/webhook step that provides a URL for the webhook notification to go to
My goal is that the Azure Function's URL receives notifications from the software's webhook and performs an action. The Azure Logic App is for testing only.
What works
When the the Azure Logic App's URL is used in the software's webhook configuration, the desired action is performed. All works as expected.
The Azure Logic App's logging shows the JSON output from the incoming webhook. I expect (but believe this may be where I am going wrong) that this is the JSON the webhook is sending to the Azure Logic App's URL. When this JSON is used in the Azure Function UI's "Test" tab > "Request body" field, the desired action is performed. All works as expected.
When the Azure Function's URL and the JSON is in a Postman request, the desired action is performed. All works as expected.
What doesn't work
When the Azure Function's URL is used in the software's webhook configuration, no action is performed. This is of course my goal. From everything I have read, I understand that this URL as a webhook endpoint should work.
Azure Function's URL
This is from Get function URL > default (Function key).
https://<app_name>.azurewebsites.net/api/content?code=<api_key>
Other Azure Function config settings
Allowed HTTP methods: GET, POST
Authorization level: Function
The JSON I believe to be coming over the webhook
{
"headers": {
"Expect": "100-continue",
"Host": "redacted",
"X-Telligent-Webhook-Sender": "redacted",
"Content-Length": "16908",
"Content-Type": "application/json; charset=utf-8"
},
"body": {
"events": [{
"TypeId": "ec9da4f4-0703-4029-b01e-7ca9c9ed6c85",
"DateOccurred": "2018-12-17T22:55:37.7846546Z",
"EventData": {
"ActorUserId": 9999,
"ContentId": "redacted",
"ContentTypeId": "redacted",
"ForumReplyId": 9999,
"ForumThreadId": 9999,
"ForumId": 9999
}
}]
}
}
I also tried with the following test code for the same results. It aligns more closely with the sample payload data provided by the software company:
What I tried
{
"events": [{
"TypeId": "ec9da4f4-0703-4029-b01e-7ca9c9ed6c85",
"DateOccurred": "2018-12-17T22:55:37.7846546Z",
"EventData": {
"ActorUserId": 9999,
"ContentId": "redacted",
"ContentTypeId": "redacted",
"ForumReplyId": 9999,
"ForumThreadId": 9999,
"ForumId": 9999
}
}]
}
Sample payload data
{
"events": [
{
"TypeId": "407ad3bc-8269-493e-ac56-9127656527df",
"DateOccurred": "2015-12-04T16:31:55.5383926Z",
"EventData": {
"ActorUserId": 2100,
"ContentId": "4c792b81-6f09-4a45-be8c-476198ba47be"
}
},
{
"TypeId": "3b75c5b9-4705-4a97-93f5-a4941dc69bc9",
"DateOccurred": "2015-12-04T16:48:03.7343926Z",
"EventData": {
"ActorUserId": 2100,
"ContentId": "4c792b81-6f09-4a45-be8c-476198ba47be"
}
}
]
}
I do not know how to determine why the Azure Function is not triggered by the webhook. The software's API documentation does not seem to provide a way to look at the JSON being sent over the webhook, although in my inexperience I may be wrong.
Is there a mechanism within Azure, or Postman, or another tool that lets me see what JSON is being sent over the webhook? Or perhaps is there another approach to determining the cause of the issue?
Thank you for any help.
This is how I got the JSON file from Azure alerts.
Install Ruby on the server
Install Sinatra with following command gem install sinatra
Create file webhook.rb and paste code bellow
require 'sinatra'
set :port, 80
set :bind, '0.0.0.0'
post '/event' do
status 204 #successful request with no body content
request.body.rewind
request_payload = JSON.parse(request.body.read)
#append the payload to a file
File.open("events.txt", "a") do |f|
f.puts(request_payload)
end
end
Run the web service with command ruby webhook.rb
JSON fill be written to file events.txt

"400 JSON parsing error" when send post to GCM

I am using Meteor for sending a request to GCM but I received message
error: 400 JSON_PARSING_ERROR
I do not understand what is wrong with my code:
options = {
"params": {
"registration_ids": "def",
"data": {"message":"abc"}},
"headers": {"Content-type":"application/json",
"Authorization": "key=AIzaSyCDCKsZ9BdJie99TC1GCdsZ1kke_oVbzw8"
}
}
HTTP.call("POST", 'https://android.googleapis.com/gcm/send', options);
I'm not familiar with meteor, but after a quick look at the doc...
What you have under params is expected to be request body, so I guess you should use content or data instead.

POST Adapter HTTP Worklight 6 500 Server Error

I am trying to register a user in my Hybrid Worklight application. For this I am using an external REST API. The API says:
Request Method: POST
Request URL: https://${domainservice}/service/plan/${planName}/user?key=${key}&tenantId=${tenantId}
Request Headers: Content-Type:application/json
Request Payload:
{
"uid": "patricia",
"firstName": "Patricia",
"lastName": "Mayo",
"pic": "BASE64_ENCODED_IMAGE"
}
Field description:
uid (required): user's uid
firstName (optional): user's first name
lastName (optional): user's last name
pic (optional): user's picture encoded as base64 string
So I created a HTTP Worklight adapter:
function RegisterUser(userid) {
var input = {
method : 'post',
path : '/service/plan/App/user',
returnedContentType : 'plain',
headers: {'Content-Type' : 'application/json'},
parameters: {
'key':'e634bc60-0c6eba577258',
'tenantId': 'd93b921d-a56c-a645924fd548'
},
body : {
'contentType' : 'application/json',
'content' : JSON.stringify({
"uid" : userid})
}
};
return WL.Server.invokeHttp(input);
}
And I get this error:
{ "errors": [
],
"info": [
],
"isSuccessful": true,
"responseHeaders": {
"$wsep": "",
"Connection": "Keep-Alive",
"Content-Language": "en-US",
"Content-Type": "text\/html;charset=ISO-8859-1",
"Date": "Wed, 30 Jul 2014 14:47:27 GMT",
"Transfer-Encoding": "chunked",
"X-Backside-Transport": "FAIL FAIL",
"X-Client-IP": "199.127.32.67",
"X-Global-Transaction-ID": "48515650",
"X-Powered-By": "Servlet\/3.0"
},
"responseTime": 357,
"statusCode": 500,
"statusReason": "Internal Server Error",
I think is very weird that I set up
headers: {'Content-Type' : 'application/json'}
but in the response it looks like
"Content-Type": "text/html;charset=ISO-8859-1"
Also I want to point out some things I have already tried:
returnedContentType : 'plain' --> It is set to plain because if I set it to json I would get a JSON parse error
body content I also tried
var payload = "{\'uid\': \'"+userid+"\'}";
payload = payload.toString();
and then 'content' : payload
Using the RESTClient of the browser everything works fine
I tried using http port 80, http port 2080, and also https 443
I also tried writting the Host in the headers
I would not be too concerned about the format of the payload in the case where the server has hit an error condition - ideally servers would give us nicely formed error response but that's not always possible. Typically, if the expected response type in case of success is JSON then that's what I specify, and I just have to have enough error handling for cases when JSON parsing fails.
As to why you're getting the 500 error ... best I can suggest is to use a network monitor of some sort to discern the difference between the request issued via Worklight and the request as issued by the Browser's REST client.
You can set this up in Eclipse, Preferences->Run->TCP/IP Monitor ...
You may want to add a Host header. I've seen numerous times where it solved similar issues. E.g. if you're trying to connect to http://www.server.com/a/b/c/d add below header to your headers property
headers: {
Host: 'www.server.com'
}
I finally found the error. There is a defect in Worklight, the query parameters are removed and put into request body so the REST SERVICE does not receive key & tenantId. This is the final working code solution. Thank you anyways for your quick answers :)
function RegisterUser(userid) {
var payload = '{"uid": \"'+userid+'\"}';
var input = {
method : 'post',
path : '/service/plan/App/user?key=e630-db87-4803-bc45-57725c&tenantId=d9348af-a56c-a645924fd54e',
returnedContentType : 'application/json',
headers: {'Content-Type' : 'application/json'},
body : {
'contentType' : 'application/json',
'content' : payload.toString()
}
};
return WL.Server.invokeHttp(input);
}

dojo/request/xhr calling Perl Web Service on different domain -getting scripting errors

I understand Dojo's XHR mechanism supports CORS but sets the X-Requested-With by default. I just have to set the headers = {"X-Requested-With":null }
So I am using dojo/request/xhr to call a Perl Web Service (Catalyst Framework)
xhr.get(url, {
handleAs: "json",
headers: {"X-Requested-With": null}
I'm using Fiddler and this is the JSON string:
{
"data" : [
{
"structure" : [
{
"name" : "State"
}
],
"dataSource" : [
{
"State" : "CA",
"Id" : 1
}
]
}
]
}
Fiddler returns an HTTP Result of 200 but I'm getting an error in dojo.then{}
"Unable to load http://Server:3000/state/ status: 0"
I also tried using dojo/request/script to call a Perl Web Service (Catalyst Framework)
script.get(url, {
jsonp: "callback"
}).then(...
But I get scripting error:
JavaScript critical error at line 2, column 11 in http://Server:3000/state/?callback=dojo_request_script_callbacks.dojo_request_script0\n\nSCRIPT1004: Expected ';'
It highlights the ":" after "data". I don't believe this ill-formed json string because my MVC controller method can call the Perl Server using WebClient's DownloadStringTaskAsync and return the value as a ContentString.
Any ideas??
If you're using CORS, you have to do more than just setting an X-Requested-With header. You also have to make sure the server sends the right headers, it had to send the Access-Control-Allow-Origin header and probably also the Access-Control-Request-Header header, for example:
Access-Control-Allow-Origin: *
Access-Control-Request-Header: x-requested-with
If you're using JSONP, your webservice must support JSONP, which means it's wrapping the entire result in a callback function.