Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you deal with dynamic resources in a RESTful context?

Tags:

rest

From what I understand of REST principles, URLs should represent a single resource, like a user or a product. How do you deal with resources that are random, or generated dynamically?

Suppose I create a resource called api.example.com/integer that returns a random integer. Would I still use GET to retrieve the integer? What would POST, PUT, and DELETE mean in this context?

What about URLs that represent behaviors? Suppose I create a resource called api.example.com/add that returns a sum of two numbers. If I wish to use this resource, do I use GET or POST to submit the numbers to be added?

like image 515
vamin Avatar asked Dec 17 '22 08:12

vamin


2 Answers

It is not required that all resources support all verbs. That is what the OPTIONS verb is for to find out what verbs are supported.

I would say either of the following are pretty self explanatory

GET http://api.example.org/RandomInteger

POST http://api.example.org/RandomNumberMachine

Either could be valid. Just be careful that a GET request may get cached. If it does then you would not be getting a random result.

One of the main principles behind REST is that you model your urls are representing nouns, not verbs. So http://api.example.com/add is not an ideal url.

You could do

GET http://api.example.org/Summation?Values=2,4

or

POST http://api.example.org/AddingMachine

with some standard format entity body that contains the numbers to add.

On the surface it may seem pretty pedantic differentiating between an url that ends with "Add" and one that ends with "summation". However, this is a pretty simple example and the REST constraint is there to guide you towards a design that has certain desirable characteristics for distributed systems.

Many years ago people would argue the difference between

apple.bite()

and

bite(apple)

was not significant. I don't think too many would dismiss the distinction these days.

like image 82
Darrel Miller Avatar answered Mar 07 '23 01:03

Darrel Miller


I think GET would be appropriate for a random number. You would simply not allow POST, PUT, or DELETE on that resource.

For the sum, why not just:

getSum?addends=3,5,8

Reponse is 16.

POST is for when you want "the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line."

In this case, there's no need for the server to permanently accept/remember the addends, so POST is not appropriate.

like image 27
Matthew Flaschen Avatar answered Mar 07 '23 01:03

Matthew Flaschen