IntelliJ HTTP Client - using a variable set from one POST request in a following JSON body of another POST request
Asked Answered
C

1

7

In HTTP client Editor on IntelliJ, I am trying to do this:

POST http://{{host}}/path-to-my-first-resource

Content-Type: application/json

{"field1":"false",
 "field2":"test",
 "field3":"test",
}

I got the result of the above POST with this:

> {%
client.global.set("my-first-returned-var", response.body.json.var1);
client.global.set("my-second-returned-var", response.body.json.var2);
client.global.set("my-third-returned-var", response.body.json.var3); 
%}

The variables have been returned with success. Thus, I am trying to use those variables in a subsequent POST, like that:

POST http://{{host}}/path-to-my-second-resource

Content-Type: application/json

{"anotherfield1":"{{my-first-returned-var}}",
 "justanother":"{{my-second-returned-var}}"
}

I tried to send the variables in the body with quotes and without quotes, but IntelliJ did not translate the variables inside double curlies. I can use the variables on HTPP Header, like:

GET https://my-request
Authorization: Bearer {{my-first-returned-var}}

But I could not use these variables in a JSON body.

The API that I'm trying to use is a Spring Boot REST Controller that use Jackson lib to deserialize the body from a request into a Java Object. The error message that Spring Boot return is something like that:

JSON parse error: Cannot deserialize instance of java.lang.String out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException

Chiasma answered 13/2, 2020 at 17:47 Comment(2)
Is there any chance that you are trying to use "Run all requests in file" link? There is a bug about it: youtrack.jetbrains.com/issue/WI-49638Esculent
@user10550971 I have been tested with Run with 'desenv' environmentChiasma
S
4

I know you asked this several months ago, but have you tried this:

client.global.set("my-first-returned-var", JSON.stringify(response.body.json.var1));
Sleeping answered 17/10, 2020 at 10:17 Comment(3)
Not sure if this answers the question. But I feel it should have landed in the comments rather than as an answer.Roshan
This definitely solved the question for anyone struggling with sending a JSON body request, that should use some variable set in a previous request (which lead me to this question). Without the stringify IntelliJ sends for example {"key": myVariable} (which is syntactically wrong JSON) instead of {"key": "myVariable"}. So more a bug in IntelliJ, but helpful workaround for this (similiar) type of requests.Alixaliza
This solved the problem for me as well.Yseulte

© 2022 - 2024 — McMap. All rights reserved.