Search code examples
c#jsonrestpostman

how to pass complex object parameters in postman?


my c# api takes two parameters, one complex object and one string:

[HttpPost, Route("paramtester")]
public string paramtester(people user, string message) {
    return user.name + message;}

how do I pass by a json object in the body? I have tried passing in a serial json object which doesn't work at all:

{
    "user": {
        "name": "John Doe",
        "age": 30,
        "country": "USA"
    },
    "message": "Hello, World!"
}

this will return:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-40ce97917410bdcff73bb4d8737ed944-2c7f4bf20348d6b7-00",
    "errors": {
        "name": [
            "The name field is required."
        ],
        "address": [
            "The address field is required."
        ],
        "message": [
            "The message field is required."
        ]
    }
}

Solution

  • There is 2 correct approaches:

    1. create a request object that contains a complex object user and a silple string message

      public class ParamTesterRequest
      {
         public People User {get; set;}
         public string Message {get; set;}
      }
      

      So your web API become

       [HttpPost("paramtester")]
       public string ParamTester(ParamTesterRequest request)
       {
          return request.User.Name + request.Message;
       }
      
    2. the other one is as said by Selvin, use the complex parameter user from body and the other one as query parameter. So your web API become

       [HttpPost("paramtester")]
       public string ParamTester([FromQuery] string message, [FromBody] People user)
       {
          return user.Name + message;
       }
      

    NOTE: the first answer is that it is the simplest and cleanest