4

I'm working on a REST API, and I can't find the best way to manage the resources URIs. When I query my API, I want something like that:

{
    'name':'foo',
    'id':100,
    'uri':'/path/to/the/resource/100'
}

Should I store the resources URI in my database or should I generate in the code when the request is treated?

Thanks

loics2
  • 616
  • 1
  • 10
  • 24
  • uri - is more like input than out put. so why do expect it in output json. Sure you can add one more key as uri and save it. but this may not be a part of response – forvaidya Aug 06 '13 at 11:01
  • Yeah it's maybe not necessary in this case, but the URI of the resources are used in collections for example. – loics2 Aug 06 '13 at 11:14

3 Answers3

1

Do not store the URI in your database.

The URI of a resource is not the resource itself. Also, you don't need to return the ID in your response. Clients have no need for it. Just return the URL for self and the URLs of any linked resources.

You may also appreciate this answer.

Community
  • 1
  • 1
Nicholas Shanks
  • 10,623
  • 4
  • 56
  • 80
0

On the API design, you shouldn't be returning URIs as part of the data in an HTTP API response. There's a header field for that if your resource is available from multiple URIs, and the domain logic of your application alongside good naming of the URIs on your part should allow guessing of the resource location.

For instance, if {'name':'foo', 'id':100} is a Foo, you (and users) would usually expect its URI to be /foos/100, so why would you need to return the URI inside the response data?

Now more pragmatically, since supporting those fancy HTTP headers could make it harder for your clients to adopt your API, I believe you should store URIs in a 1:many relationship with your resources if you expect your resources to change URI a lot (I hope they don't), so it might be easier for you to support redirects with 301 Moved Permanently for old ones. Other than that, I don't see the reason not to generate them on the fly, since you're going to have to implement redirects on old controller actions that respond to old URIs manually, assuming you're using a MVC structure.

paolobueno
  • 1,678
  • 10
  • 9
  • I understand you point, but in a REST API, you're expected to return the URI. Martin Fowler commands it: https://martinfowler.com/articles/richardsonMaturityModel.html – pyetti Aug 10 '18 at 06:43
0

From what I understand you dont store the Uri's, but specify the uri pattern on the service methods using the URI template property. For example using your link you would have:

[WebGet(UriTemplate = /path/to/the/resource/{number})]
public SomeMethod(String number)
{
   Int16.Parse(number);
   //User user = UserList(number)
}
beaumondo
  • 4,862
  • 7
  • 29
  • 42