Karate: Not able to pass header value extracted from one api response into the request header of another api - api

Here I'm storing the value of Etag into variable etag, here the values is printed correctly:
Given path '/price/v4/quote/',quoteId,'/products'
And request requestPayload
When method POST
print 'headers:', karate.prevRequest.headers
Then status 200
And def etag = responseHeaders['ETag']
print etag
[print]
["3"]
Now I'm passing it to the request header of another api:
* header If-Match = etag
Given path '/price/v4/quote/',quoteId,'/accept'
And request requestPayload
When method PUT
* print 'headers:', karate.prevRequest.headers
Then status 200
* print karate.pretty(response)
But I'm getting following error as the value of etag header comes with regex:
Got invalid quoteVersion for quote 'b25f50bc-0479-4390-b4fe-0620fc6c6139'. quoteVersion '[\"3\"]', actualVersion '3'"}

I think you missed that responseHeaders is a Map of Lists. Refer the docs: https://github.com/karatelabs/karate#responseheaders
Try this:
And def etag = responseHeaders['ETag'][0]
Also we have a better API for headers in the next versions for anyone else coming across this in the future, please refer: https://github.com/karatelabs/karate/issues/1962

Related

Karate / Post Request : Unable to pass random generator variable in json payload

I am trying to create Karate feature file for API Testing.
It is a post request and we have to pass random number for 1 field i.e. order in request payload every time.
Now, I am trying to use this function in the same feature file to pass that random generated value in json payload before sending post request.
Could someone please have a look at my feature file and help.
Thanks
Also, Is there a way if i want to pass this same random value for a json payload created as a separate request.json payload file
Your requestPayload is within double quotes, so it became a string.
Here's an example that should get you going. Just paste it into a new Scenario and run it and see what happens.
* def temp1 = 'bar'
* url 'https://httpbin.org/anything'
* def payload = { foo: '#(temp1)' }
* request payload
* method post
And please read the documentation and examples, it will save a you a lot of time.

How do I respond to the Dropbox webhook challenge in Dark?

I want to respond to a Dropbox webhook using my Dark app (https://darklang.com/)
It says I need to set some headers to respond to the challenge (https://www.dropbox.com/developers/reference/webhooks)
How do I even set headers in the response?
The trick is twofold:
You need to set the correct headers. This is tricky in Dark, especially with headers that have a dash in the name
And, you need to pull the 'challenge' out of the URL parameters and then put that in the body of the request. Try this:
let body = request.queryParams.challenge
let headers = Dict::empty
|>Dict::set "Content-Type" "text/plain"
|>Dict::set "X-Content-Type-Options" "nosniff"
let response = Http::respondWithHeaders body headers 200
response

Use header in multiple calls in the same scenario in Karate

Having a feature with only one scenario with more than one http calls, I want to use the same host and headers for all calls. However, although I am able to set the url to apply for all calls, the header seems to only be applied in the first call and then reset. Does someone have any info on why this is happening and/or a suggestion on how to do it correctly (besides adding them in each call separately)?
Either by setting them in the Background or with a generic Given, url is used in both calls, but the header is only included in the first:
1)
Feature: sample
Background:
* header Content-Type = 'application/json'
* url http://localhost:8080
Scenario: do multiple calls
Given path /sample/
When method GET
Then status 200
Given path /sample2/
When method GET
Then status 200
2)
Feature: sample2
Given header Content-Type = 'application/json'
And url http://localhost:8080
Scenario: do multiple calls
Given path /sample/
When method GET
Then status 200
Given path /sample2/
When method GET
Then status 200
You really really should read the documentation: https://github.com/intuit/karate#configure-headers
Just do:
Background:
* configure headers = { 'Content-Type': 'application/json' }
And there are many more options, just read the docs. Note that you typically never need to set the Content-Type because Karate does that automatically based on the request body.
I had the same problem. It was fixed when I added the "Header" informations I always use to the "karate-config.js".
var accessToken = karate.callSingle("classpath:helpers/authentication.feature").accessToken
karate.configure("headers",{Authorization: "Bearer " + accessToken})

Add http header in HTTPFound() with pyramid

I have a Pyramid application where I have the following line of code:
return HTTPFound(location=request.route_url('feeds'))
However I want to pass an extra parameter in the headers. Im trying with this:
headers = {"MyVariable": "MyValue"}
return HTTPFound(location=request.route_url('feeds'),headers=headers)
However the view_config of "feeds" does not get MyVariable in the headers. I'm checking it with the following code:
print "**************"
for key in request.headers.keys():
print key
print "**************"
What am I doing wrong?
headers is meant to be a sequence of (key, value) pairs:
headers = [("MyVariable", "MyValue")]
This lets you specify a header more than once. Also see the Response documentation, the headers keyword is passed on as headerlist to the Response object produced. Also see the HTTP Exceptions documentation:
headers:
a list of (k,v) header pairs
However, headers are only sent to the client; they are not passed on by the client to the next request that they are instructed to make. Use GET query parameters if you need to pass information along to the redirection target, or set values in cookies or in the session instead.
To add on query parameters, specify a _query directory for route_url():
params = {"MyVariable": "MyValue"}
return HTTPFound(location=request.route_url('feeds', _query=params))
and look for those query parameters in request.GET:
for key in request.GET:
print key, request.GET.getall(key)
Due to the way HTTP works, what you are asking is not possible. You can use either GET parameters to pass the data, or you can store the data in a cookie instead.

How to set response headers with Rikulo Stream server?

I have one API that returns information in JSON, and for that, I would indicate that the content-type of the HttpResponse is application/json.
So, with Rikulo, I have something like :
connect.response.headers.set(HttpHeaders.CONTENT_TYPE, contentTypes['json']);
But when I request my API, it told me that the headers are immutable.
HttpException: HTTP headers are not mutable
#0 _HttpHeaders._checkMutable (http_headers.dart:267:21)
#1 _HttpHeaders.set (http_headers.dart:31:18)
Therefore, how can I set my response headers, or there is a native solution with Rikulo to return JSON data ?
You can set the contentType property directly:
connect.response.headers.contentType = contentTypes["json"];
If you'd like to set the header instead, you have to pass a String object (which Dart SDK expects):
connect.response.headers.set(HttpHeaders.CONTENT_TYPE,
contentTypes['json'].toString());
But the error message shall not be as you posted. Like Kai suggested in the comment, the message indicates you have output some data before setting the header.