简体   繁体   English

验证代表REST中资源和子资源的输入

[英]Validating inputs representing Resources and Sub-resources in REST

I have a resource called user and a sub-resource called images. 我有一个称为用户的资源和一个名为图像的子资源。 To access a particular image, the only way to do it is using the URL: /users/{userId}/images/{imageId}. 要访问特定图像,唯一的方法是使用URL:/ users / {userId} / images / {imageId}。

The database schema is such that one user can have multiple images. 数据库模式使一个用户可以拥有多个图像。

The client sends us inputs for "{userId}" and "{imageId}". 客户向我们发送“ {userId}”和“ {imageId}”的输入。 I would have to validate these inputs. 我将不得不验证这些输入。 My question is pertaining to validating the "{imageId}" input. 我的问题与验证“ {imageId}”输入有关。 I have two options here: 我在这里有两个选择:

Option 1: Validate if a particular imageId belongs to that userId. 选项1:验证特定的imageId是否属于该userId。 If I see no images for the given userId, then throw an error that "There is no image for the given userId". 如果看不到给定userId的图像,则抛出错误“给定userId没有图像”。

Option 2: Validate if the image with the given "{imageId}" exists. 选项2:验证是否存在带有给定“ {imageId}”的图像。 Throw an error saying "Image with given imageId does not exist". 引发错误,指出“不存在具有给定imageId的图像”。 Then again validate (another DB check) if the given "{imageId}", belongs to that "{userId}". 然后再次验证(另一个数据库检查)是否给定的“ {imageId}”属于该“ {userId}”。

Of the two options above, which option is the right approach? 在以上两个选项中,哪个选项是正确的方法?

I have a resource called user and a sub-resource called images. 我有一个称为用户的资源和一个名为图像的子资源。 To access a particular image, the only way to do it is using the URL: /users/{userId}/images/{imageId}. 要访问特定图像,唯一的方法是使用URL:/ users / {userId} / images / {imageId}。 The database schema is such that one user can have multiple images. 数据库模式使一个用户可以拥有多个图像。

I think you misunderstood the URI structure restrictions of REST: 我认为您误解了REST的URI结构限制:

There are no restrictions about how to build URIs. 对于如何构建URI没有任何限制。

You can use your own conventions, it does not matter, because the clients are decoupled from the URI structures... For example I can say that my images are under the /images/{imageId} . 您可以使用自己的约定,这没关系,因为客户端与URI结构是分离的。例如,我可以说我的图像位于/images/{imageId} It is perfectly valid... 这是完全有效的...

You don't have to map resources to entities, and by complex applications you won't be able to do that. 您不必将资源映射到实体,并且通过复杂的应用程序您将无法做到这一点。

Of the two options above, which option is the right approach? 在以上两个选项中,哪个选项是正确的方法?

You can send back 404 with a message, that there is no resource under the URI. 您可以发送404消息,说明URI下没有资源。 Error messages about the URI structure does not mean anything to the client. 有关URI结构的错误消息对客户端没有任何意义。 URIs are opaque to the client. URI对客户端是不透明的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM