How can I create a RESTful calculator?

后端 未结 4 1061
粉色の甜心
粉色の甜心 2021-02-01 03:32

Given that RESTful web services are all based around the sacred idea that \"everything is represented as resources and can be accessed by an address (URI)\", this may make sense

4条回答
  •  [愿得一人]
    2021-02-01 04:10

    A calculator service would be simple to model in a RESTful manner. The "R" in "CRUD" stands for "read", and there's no reason that "read" can't also mean "compute". So a simple Reverse Polish calculator service could be accessed via GET:

    GET https://calc.com/rpnCalc?3&4&%2B
    7
    

    The URI scheme above simply adds three parameters to the GET request:

    3
    4
    + (URL-encoded as %2B)
    

    That's an idempotent, safe and cacheable request. If this was an insanely complicated math query that took many minutes to compute I could route these queries to an out-of-the-box HTTP proxy and use it to instantly return any pre-computed values should the same URI be queried repeatedly.

    Depending on the kinds of calculations you need to do, you could also POST a very complex query to a Calculator resource (passing in the query as the request body) and the server might return the URI to a "result" resource, which you can then GET to retrieve the results, and even paginate through them.

    Secondly, what is the real advantage of using REST over SOAP if the logic of SOAP already makes complete sense?

    I can access the above calculator service using a command-line tool like curl without building a complex piece of SOAP. I can code calls to it in seconds without having to use any third-party XML library or SOAP toolkit. I can use commodity tools like HTTP proxies to cache results and improve performance. I don't have to worry about SOAP interoperability or check for WS-I compatibility. If I use hyperlinks correctly then I can evolve and improve my service without affecting existing clients or having them to even recompile. There's no WSDL to version and no brittle contract which I have to maintain for years. The clients already know what GET/PUT/POST/DELETE do and I don't have to redefine or re-document their semantics. API clients that decide they'd prefer JSON instead of XML can get it using HTTP's inbuilt content-negotiation feature. I can do absolutely zero of these things with SOAP and Web Services.

    Hey, if SOAP fits your needs, have at it. There are many benefits to using REST but they might not be appropriate to your situation. At the very least, learn about what REST can give you with a decent book like this one and then make your mind up after getting the full story.

提交回复
热议问题