Naguib Ihab
Naguib Ihab

Reputation: 4496

Deleting with a FK using RESTful API design

I have a table called itemlink which contains three columns id,parentId,childId

According to this article if I want to get all itemlinks then I'd call GET /itemlink and if I want to get all itemlinks that belong to a particular parent then I'd add in a query string GET /itemlink?parentId=5 and that parameter is optional

But what if I'm dealing with delete and I want to give the client the ability to delete all itemlinks that belong to a particular parent, I don't feel comfortable having a url that would delete all itemlinks DEL /itemlink, that doesn't sound like best (or safe) practice so what is the best way to implement this?

One of the options I can think of to force the client to add in the parentId when asking to delete is to have a end point like /itemlink/parent/{id} but does that break the rules of a proper REST design?

Upvotes: 0

Views: 646

Answers (1)

Deva Gerald
Deva Gerald

Reputation: 334

Resources & Sub-resources are involved in your case. i.e A parent-children relationship. IMO, the relationship (itemlink) should not be exposed as a resource in REST APIs, which is actually the confusing point in your case.

I will explain this with a sample usecase similar to yours.

Customers - Parent table 
Orders - Child table
LinkId - CustomerId - OrderId - Link table

In this case, the apis have to be like

/customers/$customer_id/orders - (GET) - Get all orders of the customer
/customers/$customer_id/orders/$order_id - (GET) - Get a particular order of the customer
/customers/$customer_id/orders - (POST) - Create a new order for the customer
/customers/$customer_id/orders/$order_id - (PUT) - Edit a particular order of the customer
/customers/$customer_id/orders/$order_id - (DELETE) - Delete all the orders of the customer

And coming to deleting the FK relationship, when a customer closes his account, all the orders should be dropped, which will happen through /customers/$customer_id - HTTP DELETE

Upvotes: 1

Related Questions