Search code examples
c#jsonrestful-url

How to pass in part of object(json) by restful api


Now, I have a user object which has three required attributes: {FirstName, LastName, CreatedTime }.

Now I developed an API to create a user. I want to use POST /api/users.

I should pass in Jason data and it contains the data I want to post.

If I pass in {FirstName=abc, LastName=abc, CreatedTime=sometime}, it works, but if i miss any attribute, such like only passing in {firstname=abc}, it will throw exception.

I pasted my method below.

    [Route("api/users")]
    public User CreateUser(User user)
    {
        if (!ModelState.IsValid)
            throw  new HttpResponseException(HttpStatusCode.BadRequest);

        user.FirstName = String.IsNullOrEmpty(user.FirstName) ? "Undefined" : user.FirstName;
        user.LastName = String.IsNullOrEmpty(user.LastName) ? "Undefined" : user.LastName;
        user.UserName = String.IsNullOrEmpty(user.UserName) ? "Undefined" : user.UserName;
        user.ModifiedAt = DateTime.Now;
        user.CreatedAt = DateTime.Now;
        _context.Users.Add(user);
        _context.SaveChanges();

        return user;
    }

My question is: Is there any way that I can pass in partial properties of user? Such like {firstname=abc}.

This technique can also be used as PUT (update user method).

Thanks in advance.


Solution

  • 1) When inserting your record just mark your CreatedAt and ModifiedAt property to [JsonIgnore] attribute

    [Required] 
    [JsonIgnore] 
    public DateTime CreatedAt { get; set; } 
    
    [Required] 
    [JsonIgnore] 
    public DateTime ModifiedAt { get; set; } 
    

    2) When you try to get your data your api method will be

    [HttpGet]
    [Route("ById/{id=id}")]
    public IHttpActionResult GetUser(int? id)
    {
        if (id == null)
            return NotFound();
    
        User user = _context.Users.SingleOrDefault(c => c.UserId == id.Value);
    
        if (user == null)
            return BadRequest("User not exist in our database");
    
        var returnedData = new { FirstName = user.FirstName, LastName = user.LastName, UserName = user.UserName, CreatedAt = DateTime.Now, ModifiedAt = DateTime.Now };
        return Ok(returnedData);
    }
    

    We just use to return Anonymous Type that is customizable to return data.

    Try once may it help you