0

I'm trying to create a new user using a pre-request script to be able to use a PUT request to edit user profile settings independently from other requests.

So I'm setting a token from the response to my env variable to use it in the header for the PUT request.

My whole pre-request script is not working - new user is not created and new token is not set. What am I missing?

const createUser = pm.environment.get('url') + 'users'

pm.sendRequest({
    url: createUser,
    method: 'POST',
    header: {
        'Content-type': 'application/json',
        'X-Foo': 'bar'
    },
    body: {
        mode: 'application/json',
        raw: JSON.stringify({"user":{
            "username":"{{$randomUserName}}",
            "email":"{{$randomEmail}}",
            "password": "Pa$$w0rd!"}
            })
    }
})

pm.sendRequest(function (err, response) {
    pm.environment.set("tokenConduit", response.json().token);
});

2 Answers2

1

I think this is incorrect:

body: {
    mode: 'application/json',
    raw: JSON.stringify({"user":{
        "username":"{{$randomUserName}}",
        "email":"{{$randomEmail}}",
        "password": "Pa$$w0rd!"}
    })
}

application/json goes into Headers like you have it, but the body is in raw format. See the example in Postman docs. You stringify a json, so it's just a bunch of charaters, mode "application/json" doesn't exist.

Another thing is you're sending 2 requests, but I think you want to send only one:

const request = {
    url: createUser,
    method: 'POST',
    header: {
        'Content-type': 'application/json',
        'X-Foo': 'bar'
    },
    body: {
        mode: 'application/json',
        raw: JSON.stringify({"user":{
            "username":"{{$randomUserName}}",
            "email":"{{$randomEmail}}",
            "password": "Pa$$w0rd!"}
        })
    }
};

pm.sendRequest(request, function (err, response) {
    pm.environment.set("tokenConduit", response.json().token);
});

So you should have only one pm.sendRequest() in your code.

pavelsaman
  • 7,399
  • 1
  • 14
  • 32
0
const createUser = 

pm.sendRequest({
    url: "https://reqres.in/api/users?page=2",
    method: 'POST',
    header: {
        'Content-type': 'application/json',
        'X-Foo': 'bar'
    },
    body: {
        mode: 'application/json',
        raw: pm.variables.replaceIn(JSON.stringify({"user":{
            "username":"{{$randomUserName}}",
            "email":"{{$randomEmail}}",
            "password": "Pa$$w0rd!"}
            }))
    }
})

pm.sendRequest(function (err, response) {
    pm.environment.set("tokenConduit", response.json().token);
});

you have to use pm.variables.replacein to use variables inside script section,

Goto console to see what was actually send:

enter image description here

PDHide
  • 18,113
  • 2
  • 31
  • 46