0

I'm creating a restful api for the first time. Let's start with an example: I have a product, that can be linked to multiple categories.

On the client side I want just one form where I can fill in the product details, and I have a multiple selector where I can select my categories.

What's the best practice to handle such a thing. Do I post/put my data to one api call /api/product and handle there the categories. Or do I split the category-selection and product-details in the client and do I create 2 api-calls (one for the product details, one for the category-selection).

I'm looking for the best option here. Both are possible. And just one api call would be the easiest. But I strictly restful, I need 2 &pi-calls...

thanks for your answers!

Wim
  • 41
  • 3

2 Answers2

0

I don't see anything wrong with a single API call.

So you can do a POST / PUT to /api/product and pass the product details and the categories that the product belongs to as parameters.

In case of a Add, I am assuming you will do a POST to /api/product and pass parameters like product name, price,etc along with a list of categories.

Similarly in case of an Update, you could do a PUT to /api/product/<productid> and pass in the parameters as above.

Romin
  • 8,708
  • 2
  • 24
  • 28
0

The 'product' is the resource here.

Hence 'api/products' gives the list of products. The 'api/products/{{id}}' gives the details of a product.

One idea is to treat category is a resource itself. And each product subscribe to zero or more categories. So 'api/categories' gives a list of categories. Now you have another resource say 'product_subscription' which maps the product to the category. That is 'api/product_subscriptions' gives you a list like this:

{
    "productId":"someid"
    "categoryId":"some_category_id1"
},
{
    "productId":"someid"
    "categoryId":"some_category_id2"
},
{
    "productId":"someid"
    "categoryId":"some_category_id3"
}

You can further filter this list using the query params.

Neeraj Krishna
  • 1,527
  • 2
  • 16
  • 22