restvisual-studio-codejwtvscode-extensionsvscode-restclient

VSCode REST Client : use the result of a request in another request


Using VSCode Rest Client, I would like to do a post request that returns a jwt token and use it in another GET request

For the moment I am doing this POST request in a file auth.http:

# Login
# @name tokenAPI
POST {{baseUrl}}/login HTTP/1.1
Content-Type: application/json

{
    "Username": "myuser",
    "Password": "mypassword"
}

I get this answer:

HTTP/1.1 200 OK
Connection: close
Content-Type: application/json; charset=utf-8
Date: Sat, 16 Dec 2023 14:16:45 GMT
Server: Kestrel
Transfer-Encoding: chunked

{
  "token": "theheader.thepayload.thesignature"
}

I have this settings with a authToken where I have to enter manually the value for authToken each time it changes, in the correct environment.

In the file .vscode/settings.json, I have:

{
    "rest-client.environmentVariables": {
        "local": {
            "baseUrl": "http://localhost",
            "authToken": "theheader.thepayload.thesignature"
        },
        "docker": {
            "baseUrl": "http://localhost:8080",
            "authToken": "",
        },
        "prod": {
            "baseUrl": "http://produrl.net",
            "authToken": "",
        }
    }
}

I have another request in user.http:

GET {{baseUrl}}/User
Authorization: Bearer {{authToken}}

I would like to store the response of the POST authentication request and reuse it in other requests, it would be something like this:

# Login
# @name tokenAPI
POST {{baseUrl}}/login HTTP/1.1
Content-Type: application/json

{
    "Username": "myuser",
    "Password": "mypassword"
}


@authToken = {{tokenAPI.response.body.token}}

Do you know how to do this?


Solution

  • If you stay in the same file, a solution is

    In a request file named for example user.http

    @baseUrl = http://localhost
    # Login
    # @name tokenAPI
    POST {{baseUrl}}/Auth/login HTTP/1.1
    Content-Type: application/json
    
    {
        "Username": "myuser",
        "Password": "mypassword"
    }
    ###
    
    @authToken = {{tokenAPI.response.body.token}}
    # Get User
    # @name getUser
    GET {{baseUrl}}/User
    Authorization: Bearer {{authToken}}