Set response headers - hapi.js

I need to set some response headers within server.onPreHandler ext method.
There are 2 scenarios, where I need this happen when user sends an API request to my route end point.
1) In success scenario, I need to set headers and let process continue further down life cycle
2) In error scenario (where user has not provided a required field), I need to set headers and return immediately to user with appropriate error info.
In both of these scenarios, I would like to set response headers.
In the 2nd scenario above, I am able to invoke reply.response('error') and then set response header to it using response.header('x', 'value'). However, in the 1st scenario, where before calling reply.continue() I am trying to set header using request.response.header('x', 'value), I get response null error.
Please help
Thanks
Ramesh

I'm able to change response headers like this. Have you tried this way?
// at your onPreResponse ext body
const response = request.response;
if (request.response.isBoom) {
response.output.headers['x'] = 'value';
} else {
response.header('x', 'value');
}

Related

Is there a way for postman to read the response data from a GET request and then use an IF THEN statement to run a POST request?

I am trying to run a script where postman sends a Get request, and if the get response contains a certain variable to then run a Post request. How do i do this?
(also is there a way to run a get request hourly)
In pre-requisite add:
// set initial value
const method = pm.variables.get("method")
// set initial value as GET if method is undefined
method ? null : pm.variables.set("method", "GET")
// Set this as method
pm.request.method =method
in test script add :
// the condition check
if (pm.response.json().somevalue === "somevalue") {
//then change the method
pm.variables.set("method", "POST")
//call the same request again using setNExtRequest
// pm.info.reqeustName gives current request's name
postman.setNextRequest(pm.info.requestName)
}

How to I get the detail (custom error message) returned with a bad request status code? So that I can do an ASSERT on it

Hi so I am setting up some Integration tests (using Xunit) and I would like to run an Assert to check whether the correct custom error message is returned.
This is the data I need to get is in the following response see image...
detail: "Username must be unique" Don't worry this message will be modified to be more useful later on I am just wanting to get it working first
Required Info
This is the current code...
//Act
response = await _httpClient.PostAsync("CompleteUserSetup", formContent);
//Assert
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode) ; //Bad request should be returned
//TODO: check custom error message is correct
So hoping for...
ASSERT.Equal("Username must be unique", some code to get detail from response)
Okay so I figured out how to get the data I needed. I just needed to convert the result into an object and then I was able to pull the detail data that I needed.
var resultModel = await System.Text.Json.JsonSerializer.DeserializeAsync<Result>(response.Content.ReadAsStream(), JsonSerializerHelper.DefaultDeserialisationOptions);
var errorMessage = resultModel.detail;

How to get value from response body by using environment variable

This is my response body, I want to get the value of status by using an environment variable.
{
"success":[
{
"code":"200",
"message":"Success",
"details":"Station was retrieved successfully."
}
]
}
i can get value of status code as: jsonData.success.code,
But instead of this, I'm doing it like,
I m setting an environment variable named 'sh' n I gave value as "code"...
pm.environment.set("sh","code");
var s = pm.environment.get("sh")
jsonData.status.success[0].s
By doing like this I'm not able to get the path...Any solutions?
Thanks in advance.
It's hard to tell what your actual response body is but this should probably work:
let statusCode = pm.response.json().success[0].code
pm.environment.set("statusCode", statusCode)
Ensure that you create an environment file before running the request.

How to pull data from CATSone API with Authentication Token?

I am completely new to coding. I am trying to build a dashboard in Klipfolio. I am using a CATSone API to pull data from CATSone to Klipfolio. However, I can only get 100 rows a time, which means I would have to pull data 2600 times.
I am now trying to build a script to get data from the API through Google Script Editor. However, since I have no experience in this, I am just trying stuff. I watched some videos, also from Ben Collins. The basis is simple, and I get what he is doing.
However, I have a problem with putting the API key.
var API_KEY = 'key'
function callCATSone(){
//Call the CATSone API for all candidate list
var response = UrlFetchApp.fetch("https://api.catsone.nl/v3/candidates");
Logger.log(response.getContentText());
// URL and params for the API
var url = 'https://api.catsone.nl/v3/candidates';
var params = {
'method': 'GET',
'muteHttpExceptions': true,
'headers': {
'Authorization': 'key ' + apikey
}
};
// call the API
var response = UrlFetchApp.fetch(url, params);
var data = response.getContentText();
var json = JSON.parse(data);
}
In the end, I would like to transfer all candidate list data to my sheets. Therefore, I call on the API with Authorization key. After that, I will manipulate the data, but that's for later. The first problem I now encounter, is this fail code:
'Verzoek voor https://api.catsone.nl/v3/candidates is mislukt. Foutcode: 401. Ingekorte serverreactie: {"message":"Invalid credentials."} (Gebruik de optie muteHttpExceptions om de volledige reactie te onderzoeken.) (regel 6, bestand 'Code')'.
I expect to get a list of all data from CATSone into my sheets.
Does anyone know how I can accomplish this?
Two changes should fix the credentials error:
Authorization header should be Authorization: 'Token ' + yourApiKey instead of 'key ', see the v3 API documentation https://docs.catsone.com/api/v3/#authentication.
API key in your case is stored in a global variable API_KEY, you should reference it exactly like that, not as an apikey (unless there is a typo in your sample or some missing code): Authorization : 'Token ' + API_KEY.
Btw, it should probably set either a Content-Type header or a contentType parameter for UrlFetchApp.fetch() method call to application/json as UrlFetchApp.fetch() request content type defaults to application/x-www-form-urlencoded.
If you plan to continue working with APIs, it would be beneficial to read this MDN article.

Request and Response Headers Override using Restler

I am new to restler and trying to do the following things, can't seem to get hold of it
I have this class and method exposed via Restler
class Account {
protected $Api_Version = array('version' => "1.0.2.1234", 'href' => "/");
// Returns the version of the service
// Content-Type: application/vnd.cust.version+json
function version() {
return json_encode($this->version);
}
// Accepts only Content Type: application/vnd.cust.account+json
function postCreate() {
}
}
1) I want to return my own Content-Type to client like in the 'version' method instead of default application/json. In my case its 'application/vnd.cust.version+json'
2) Method postCreate should only accept the request if the Contet-Type is set to 'application/vnd.cust.account+json'. How to check if that header is set in the request.
3) Also in the restler API Explorer, for methond name, how can I show only the method name instead of the 'version.json'. I want to show just 'version' like the method name
Thank you for your help.
Narsi
1) maybe Write your own format? Take a Look at
http://restler3.luracast.com/examples/_003_multiformat/readme.html
2) you could check the headers and throw Exception on wrong one.
Take a Look at this link
http://stackoverflow.com/questions/541430/how-do-i-read-any-request-header-in-php
3) have you tried to and the following line to your Index.php?
Resources::$useFormatAsExtension = false
Hope takes you further on :)
CU
Inge