Rest service vs basic function

45 views Asked by At

i am confused with REST. I have a service which transforms a json into a excel file. This is a service, and doesnt represent an entity and thus has no state.

Is it OK to create a REST service for this with HTTP GET or what is the best practice to add such service to our collection of restful services?

... It is not a GET POST or PUT and it is not a resource and has no state. It is just a method, a function. So such functionality conflucts with the REST paradigm, right? So what and how to design or implement this properly?

2

There are 2 answers

0
Graeme Muir On

This sounds like a POST call. You are creating an object which in this case in an Excel document. The only quirk here is that the server does not save an instance of it. However, this could be future functionality and the API would still make sense if you decided to save the spreadsheets (Although the response would then need to include an Id or URL to get back to the newly created resource)

The only decision at this stage would be deciding what the name of the endpoint will be. If this was a service that could create any type of generic spreadsheet from a JSON object it could resemble the following.

Post /API/Spreadsheet

A GET call in this context wouldn't make sense since there is nothing preexisting that someone can retrieve. PUT wouldn't make sense since we are not updating an existing entity.

1
Evert On

If you have a path/endpoint in your service that returns a spreadsheet, the most appropriate method to use is GET, because you are retrieving the spreadsheet.

For REST it doesn't really matter if the spreadsheet is created on the fly. From the perspective of the protocol the excel file is a representation of your 'state' and a client retrieves the representation typically with GET. The client doesn't know and doesn't care if the spreadsheet existed as a physical file before the request was made.

That's not to say that POST is completely wrong from a HTTP perspective, but it's not correct if you follow REST best practices.

However: since you say that you're 'transforming' a JSON object, the question is... where does that JSON object live. Is the client sending it, or is it already on the server.

If the client is submitting the JSON, and the server then transforms it to excel, then you need a 2-step process:

  • PUT or POST to create a resource that contains the .json. If you used POST, you can use the Location header to indicate where the resource was created.
  • Followed-up with a GET request that has an Accept header for the excel mime-type.

If you don't want 2 requests, I don't think there's an appropriate RESTful way to do this, and you might want to fall back to just a single POST request and accept it's not RESTful.

However, I've seen some people use the Prefer: return=representation header to combine the POST and GET request into a single step.