1

I created an ASP.NET Core Web API project with Entity Framework Core and scaffolded a new "API controller with actions, using Entity Framework" and, while it's wonderful, I get the feeling the default PUT and POST methods are swapped and would like some feedback on the matter:

    // PUT: api/Items/5
    // To protect from overposting attacks, enable the specific properties you want to bind to, for
    // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
    [HttpPut("{id}")]
    public async Task<IActionResult> PutItem(long id, Item Item)
    {
        if (id != Item.Id)
        {
            return BadRequest();
        }

        _context.Entry(Item).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!ItemExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

    // POST: api/Items
    [HttpPost]
    public async Task<ActionResult<Item>> PostItem(Item Item)
    {
        _context.Items.Add(Item);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetItem), new { id = Item.Id }, Item);
    }

    private bool ItemExists(long id)
    {
        return _context.Items.Any(e => e.Id == id);
    }

As far as I know PUT should provide an object to be added to the database, while PATCH should be used to update an existing object. But from what I see in this code PUT is being used to update an already existing item, specifying an id that must already exist, while POST just uploads a new resource, without specifying any id, how I imagine a PUT should work.

Am I wrong or should I swap the HttpPut for HttpPatch and the HttpPost for HttpPut?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Shrodinger
  • 149
  • 1
  • 8
  • 3
    In general in rest API, `POST` is to create, `PUT` to modify an entire existing object using its id and `PATCH` to modify only some fields of the object, also by using its id. There is a lot more information here: https://stackoverflow.com/q/28459418/3797799 – colinD May 25 '20 at 13:01
  • There's no confusion. POST creates, PUT updates. That's what those two methods do too. This PUT updates the stored record with the contents of the `Item` object. To do that, it attaches the object to the DbContext in the `Modified` state. EF will generate a SQL query that updates all fields using the values in `Item`'s properties – Panagiotis Kanavos May 25 '20 at 13:09

1 Answers1

0

You can use PUT to create or update a resource which you know its URL. So consider the URL is /user/123 if there exists an object in that position, the PUT will simply update the data, if not the request will create a new user under path /user/123.

If you wish to update the object entirely (i.e. all its fields) you use PUT, if you want to update a single field of the resource, go for PATCH.

Whereas POST method is used to add a new resource which you don't know its URL. So you're request URL will be /user as you don't know the target.

Hope this helps!

Mouna
  • 316
  • 4
  • 14