RESTful design of convert, calculate
Asked Answered
A

2

5

How to design operations like:

  • calculate
  • convert
  • translate

For example: convert from "EUR" to "CNY" amount "100".

Is this /convert?from=EUR&to=CNY&amount=100 RESTful ?

Alameda answered 29/11, 2016 at 8:53 Comment(0)
D
6

There is nothing in

/convert?from=EUR&to=CNY&amount=100

that is not RESTful. You can say that this identifies a REST Resource.

But it looks like RPC (Remote Procedure Call) over HTTP which, in cases not as simple as currency conversion, will lead to a system that is not RESTful.

Always ask yourself: What are my Resources?

One answer could be: The Resource is the conversion result, identified by the two currencies and the amount. Then it would look more RESTful if you use

/conversion?from=EUR&to=CNY&amount=100

Note that the path is a noun (conversion), not a verb (convert). In general, if you can name a REST Resource with a noun, you are on the right track.

It is a matter of taste if you put the identifying bits into query parameters (?from=EUR&to=CNY&amount=100) or in the path. You could use

/conversion/EUR/100/CNY

using three path parameters:

/conversion/{FROM}/{AMOUNT}/{TO}
Dudek answered 29/11, 2016 at 9:23 Comment(0)
O
1

Convert

Your API looks fine to me:

/convert?from=EUR&to=CNY&amount=100

Lutz Horn's answer also gives a good alternative.

Calculate

If your API has to handle complex or lengthy operations, it might be a good idea to use POST:

/calculate

You can include the calculation in the request. This saves you from including long calculations in your URL.

If your API has to handle simple operations then you can use this design:

/calculate/add/?param1=value1&param2=value2

Similarly for subtract, multiply, divide, etc.

/calculate/subtract
/calculate/multiply
/calculate/divide

Translate

For translation, I like Google Translate's API design:

/translate/{source}/{target}/value

Here, source is your source language (say EN) and target is your target language (say HI).

In the end, your API design comes down to your choice.

Overt answered 29/11, 2016 at 10:56 Comment(1)
'You can include the calculation in the request'. That would be RPC, not REST. What is the REST resource in this case?Dudek

© 2022 - 2024 — McMap. All rights reserved.