Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
926 views
in Technique[技术] by (71.8m points)

rest - RESTful way to create multiple items in one request

I am working on a small client server program to collect orders. I want to do this in a "REST(ful) way".

What I want to do is:

Collect all orderlines (product and quantity) and send the complete order to the server

At the moment I see two options to do this:

  1. Send each orderline to the server: POST qty and product_id

I actually don't want to do this because I want to limit the number of requests to the server so option 2:

  1. Collect all the orderlines and send them to the server at once.

How should I implement option 2? a couple of ideas I have is: Wrap all orderlines in a JSON object and send this to the server or use an array to post the orderlines.

Is it a good idea or good practice to implement option 2, and if so how should I do it.

What is good practice?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I believe that another correct way to approach this would be to create another resource that represents your collection of resources. Example, imagine that we have an endpoint like /api/sheep/{id} and we can POST to /api/sheep to create a sheep resource.

Now, if we want to support bulk creation, we should consider a new flock resource at /api/flock (or /api/<your-resource>-collection if you lack a better meaningful name). Remember that resources don't need to map to your database or app models. This is a common misconception.

Resources are a higher level representation, unrelated with your data. Operating on a resource can have significant side effects, like firing an alert to a user, updating other related data, initiating a long lived process, etc. For example, we could map a file system or even the unix ps command as a REST API.

I think it is safe to assume that operating a resource may also mean to create several other entities as a side effect.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...