Sha-Pai Li
Sha-Pai Li

Reputation: 167

Post or Put multiple items in a single request

Is it possible to Post or Put more than a single item at a time, in a single request?

From

GET  /api/books Get all books.

POST /api/books Create a new book.

PUT /api/books/{id} Update an existing book.

To

POST /api/books Create books.

PUT /api/books  Update books.

Upvotes: 2

Views: 1228

Answers (2)

Sha-Pai Li
Sha-Pai Li

Reputation: 167

Finally I use like below's code.

   // Post Multi
    // POST: api/books
    [Route("api/books")]
    [ResponseType(typeof(IEnumerable<Book>))]
    public IHttpActionResult Postbooks(IEnumerable<Book> books)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        foreach (var item in books)
        {
            db.Book.Add(item);
        }

        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateException)
        {

            throw;

        }

        return Ok(books);
    }

Upvotes: 0

Yannick Meeus
Yannick Meeus

Reputation: 5890

Let's say you have a class called Book, defined as:

public class Book
{
    public string Title { get; set; }

    public string Author { get; set; }
}

Now we have a simple Web.Api controller with a POST method:

public class BooksController : ApiController
{
    [HttpPost]
    [Route("books")]
    public HttpResponseMessage PostBooks([FromBody] IEnumerable<Book> books)
    {
        return Request.CreateResponse(HttpStatusCode.Created);
    }
}

The method doesn't do anything with the data, it's purely so it compiles and runs. My first attribute indicates this is a POST, the second attribute determines the route, I'm using attribute based routing because I just like it more, but you can roll your own routing rules.

Now the PostBooks method takes in a parameter of type Ienumerable<Book>, not just a single parameter of type Book.

When I now stand up this little endpoint, and hit it with the following url:

http://localhost:port/books

And specify the request to be a POST and supply the following payload in the body of the request:

[  
   {  
      "Title":"This is a book",
      "Author":"Joe Bloggs"
   },
   {  
      "Title":"This is a book: The reckoning",
      "Author":"Joe Bloggs"
   }
]

My breakpoint is hit and Web.API managed to deserialize my payload into the books parameter when it comes into the PostBooks method:

booksDeserialized

The same applies for a PUT, the only thing that needs changing is the attribute.

Upvotes: 2

Related Questions