RESTful way to send commands

后端 未结 3 1913
走了就别回头了
走了就别回头了 2020-12-12 13:40

How do you send \"commands\" to a RESTful server?

Use case: My server caches certain information so that it does not have to read the database every time that inform

相关标签:
3条回答
  • 2020-12-12 14:07

    I have come across such a situation a lot in a past project. Since REST is well...about resource, it is not always clear how to deal with things that are Really RPC in nature.

    An easy way to get around this is to think of it as the bureaucratic part of rest, the request can be a resource itself :

    1 . "You want to trigger a command on my server ? first fill this form I90292 and send it to us" :

    POST /bureaucracy/command-request 
    Content-Type: application/x-www-form-urlencoded
    Content-Length: ...
    
    1. "Ok we will see what we can do. your case number is 999"

      201 Created (or 202 Accepted as per Kugel's comment) Location /bureaucracy/command-request/999

    2. And then the client checks regularly

      GET /bureaucracy/command-request/999

    Hopefully he gets a response like the following

    200 OK
    <command-request>
      <number>999</number>
      ...
      <result>Success</result>
    </command-request>
    

    Of course if the bureaucratic service has great customer care it would offer the customer to call him when it is done if he wants :
    "You want to trigger a command on our server? Kindly fill this form and send it to us. Note that you can join your contact info so we can call you when it is done"

    POST /bureaucracy/command-request?callback=client.com/bureaucracy/inbox 
    

    Or as a custom http header X-Callback: http://client.com/bureaucracy/inbox

    0 讨论(0)
  • 2020-12-12 14:10

    In your case, why not make the cache the resource?

    DELETE /cache
    

    When you want to flush it.

    POST /cache
    

    when you want to create a new one.

    Or combine the previous two into the following:

    DELETE /cache?autorecreate=true
    
    0 讨论(0)
  • 2020-12-12 14:24

    I'd suggest this:

    • Create a resource that you can GET which will tell you client how to send the command, similar to an HTML form, using a POST if there are side-effects to this command.
    • POST to the resource to trigger the command and return the URI to a new resource you create during the execution of this POST request (e.g. http://server.example/results/00001), perhaps with a 204 (No Content) status and Location header or a redirect (depending on which client can understand).
    • Let the client check the results on this resource using GET. You may also return the representation for this resource (or something similar) as the entity returned by the POST just before.

    It's up to you to decide on the lifecycle of the result resource. It could be short-lived if you don't need to store the results for long. The URI could be constructed from a UUID for example.

    0 讨论(0)
提交回复
热议问题