REST URI convention - Singular or plural name of resource while creating it

前端 未结 22 2201
长情又很酷
长情又很酷 2020-12-02 03:35

I\'m new to REST and I\'ve observed that in some RESTful services they use different resource URI for update/get/delete and Create. Such as

  • Create - using
22条回答
  •  时光说笑
    2020-12-02 04:03

    From the API consumer's perspective, the endpoints should be predictable so

    Ideally...

    1. GET /resources should return a list of resources.
    2. GET /resource should return a 400 level status code.
    3. GET /resources/id/{resourceId} should return a collection with one resource.
    4. GET /resource/id/{resourceId} should return a resource object.
    5. POST /resources should batch create resources.
    6. POST /resource should create a resource.
    7. PUT /resource should update a resource object.
    8. PATCH /resource should update a resource by posting only the changed attributes.
    9. PATCH /resources should batch update resources posting only the changed attributes.
    10. DELETE /resources should delete all resources; just kidding: 400 status code
    11. DELETE /resource/id/{resourceId}

    This approach is the most flexible and feature rich, but also the most time consuming to develop. So, if you're in a hurry (which is always the case with software development) just name your endpoint resource or the plural form resources. I prefer the singular form because it gives you the option to introspect and evaluate programmatically since not all plural forms end in 's'.

    Having said all that, for whatever reason the most commonly used practice developer's have chosen is to use the plural form. This is ultimately the route I have chosen and if you look at popular apis like github and twitter, this is what they do.

    Some criteria for deciding could be:

    1. What are my time constraints?
    2. What operations will I allow my consumers to do?
    3. What does the request and result payload look like?
    4. Do I want to be able to use reflection and parse the URI in my code?

    So it's up to you. Just whatever you do be consistent.

提交回复
热议问题