How can I create a RESTful calculator?

后端 未结 4 1062
粉色の甜心
粉色の甜心 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:14

    An HTTP POST doesn't necessarily have to create a persisted resource. In RFC 2616, section 9.5 we find:

    The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.

    This means we can think about "creating a calculation" without having to persist the result of that calculation at it's own URL. Your API could look like this:

    Request:
    POST /calculations
    Content-Type: text/plain
    
    3 + 3 / 12 ^ ( 3 * PI)
    
    Response:
    200 OK
    Content-Type: text/plain
    
    3.005454
    

    This has the benefit that you're not passing "content" through the URL, which will break when you try to submit a long calculation through a client or proxy with limited length for URLs. You could also make support different representations for requests and responses.

提交回复
热议问题