RESTful url to GET resource by different fields

2020-03-21 08:22发布

问题:

Simple question I'm having trouble finding an answer to..

If I have a REST web service, and my design is not using url parameters, how can I specify two different keys to return the same resource by?

Example I want (and have already implemented)

/Person/{ID}

which returns a person as expected.

Now I also want

/Person/{Name}

which returns a person by name.

Is this the correct RESTful format? Or is it something like:

/Person/Name/{Name}

回答1:

You should only use one URI to refer to a single resource. Having multiple URIs will only cause confusion. In your example, confusion would arise due to two people having the same name. Which person resource are they referring to then?

That said, you can have multiple URIs refer to a single resource, but for anything other than the "true" URI you should simply redirect the client to the right place using a status code of 301 - Moved Permanently.

Personally, I would never implement a multi-ID scheme or redirection to support it. Pick a single identification scheme and stick with it. The users of your API will thank you.

What you really need to build is a query API, so focus on how you would implement something like a /personFinder resource which could take a name as a parameter and return potentially multiple matching /person/{ID} URIs in the response.



回答2:

I guess technically you could have both URI's point to the same resource (perhaps with one of them as the canonical resource) but I think you wouldn't want to do this from an implementation perspective. What if there is an overlap between IDs and names?

It sure does seem like a good place to use query parameters, but if you insist on not doing so, perhaps you could do

person/{ID} 

and

personByName/{Name}


标签: rest