user266003
user266003

Reputation:

Building restful urls

Let's say I have dogs and cats, they have color, weight and name. Each of the animal can be identified using only color, weight and name together and, of course, their colors, weights and names are not unique, meaning can have the same values. There might be some other animal types added in the future.

What URI would you use for CRUD operations in Web REST API service?

/api/v1/animals/dogs/black/12/jack    
/api/v1/animals/type/dogs/color/black/weight/12/name/jack
/api/v1/animals?type=dogs&color=black&weight=12&name=jack  

or something else?

Upvotes: 0

Views: 197

Answers (2)

Ming Chan
Ming Chan

Reputation: 1948

Updated:

An URL should be for specifying the ‘resources’ that the API is to manage.

The resource is ‘animals’ (cats/dogs/…) and they are uniquely identified by type/color/weight/name.

Before going into URL design, need to define the ‘business’ operations; otherwise, how the URL is designed has no relevant.

Assume you will need the following business operations

  • A) Create an animal
  • B) Get info of an animal
  • C) Get info of all or subset of animals
  • D) Update an animal

id still can be used (generated) if that provide benefit; otherwise, it can be kept at the server side and not exposed to the client. Either way it still works..

A) Create an animal

POST: /api/v1/animals/dogs/black/12/jack/
RETURN: id: <id>

OR

POST: /api/v1/animals/dogs 
BODY: {‘color’ : ‘black’, ‘name’ : ‘jack’, ‘weight’ : 12 } 
RETURN: id: <id> 

B) Get info of an animal

GET: /api/v1/animals/<id>/

OR

GET: /api/v1/animals/dogs/black/12/jack/

C) Get info of all or subset of animals

GET: /api/v1/animals/dogs/

OR

GET: /api/v1/animals/dogs/black/

D) Update an animal

PUT: /api/v1/animals/<id>
BODY: {‘name’ : ‘jackjunior’}

OR

PUT: /api/v1/animals/dogs/black/12/jack/
BODY: {‘name’ : ‘jackjunior’}

Happy designing!

Upvotes: 0

Oleksi
Oleksi

Reputation: 13097

To me

/api/v1/animals?type=dogs&color=black&weight=12&name=jack

makes the most sense. With RESTful APIs you are accessing resources, and the resource here is "animals". The other fields are really human interpret-able attributes, as opposed to a unique identifier for getting back a single animal.

To make it more clean, you might want to consider giving each animal a single identifier to retrieve the resource /api/v1/animals/{id} and treat the other API as a search.

Upvotes: 1

Related Questions