سؤال

This question relates to a somewhat more specific case than the one discussed in How can I create a RESTful calculator?

It should be assumed that the values to be calculated are not simple integers, but large and complex puzzles. Such a puzzle can also contain several subpuzzles. Both can be stored/read as resources on/from a server, like:

GET /myApi/puzzle/{puzzleID}
GET /myApi/puzzle/{puzzleID}/subpuzzle/{subpuzzleID}

Afterwards, clients can trigger a calculation of them on the server. As in the above link, the resources would be located in the body of a POST request. Instead of getting and sending the puzzles, i want to refer to the already existing ones on the server. My current solution is to reference them via their URI.

This request triggers a calculation of the puzzle (and all contained subpuzzles) with ID=123:

Request:
POST /myApi/puzzleSolver
Content-Type: text/plain

/myApi/puzzle/123

This request triggers just a calculation of the subpuzzle with ID=321 in the aforementioned puzzle:

Request:
POST /myApi/puzzleSolver
Content-Type: text/plain

/myApi/puzzle/123/subpuzzle/321

Is it advisable to directly specify the resource URI in the request body - am I missing any pitfalls? Is there a better alternative, e.g. to use the puzzleID and subpuzzleID?

هل كانت مفيدة؟

المحلول

Specifying a url is not a good way of identifying a resource.

Internally your puzzle solver code will be abstracted from the puzzle retrieval code. It may not even use a REST resource to retrieve the puzzles. Maybe it goes directly to a database. Maybe its using version 2 of the api and the path has changed.

The resource url domain, path and structure are not concerns of the puzzle calculator. It will call puzzleRepo.GetPuzzle(123) or something and therefore have to extract the puzzle id from your url. Therefore you should send just the ids of the puzzles in the body of the request

POST /api/CalculatePuzzleResult
{
   "PuzzleId":"123",
   "IncludeSubPuzzles" : true
   //whatever other data is required
}

نصائح أخرى

Using the resource paths in requests looks very reasonable. It's immediately obvious what they mean, and parsing shouldn't be more difficult than alternative formats. If you want to unify stored and ad-hoc puzzles, you could use JSON payload somewhat like this:

(stored)

{
  "link":"/myApi/puzzle/123"
}

(ad-hoc)

{
  "field1":"puzzle data",
  ...
}

But that's just one possible way to do it. Another option would be to use different content-type values for links to stored puzzles versus ad-hoc puzzles, but I didn't spontaneously find a MIME type for resource links, so maybe there's no such thing.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى softwareengineering.stackexchange
scroll top