javaspringrestapi-design

REST API URL pattern design


I am currently developing a REST API.

I am developing an API that returns products associated with a user, and an API that returns products associated with a product.

I can not be sure how to configure the URLpattern to be correct.

What I think is ambiguous is that in the case of the URL returning the product list through the product, the products are repeatedly listed.

Please advise me of a good URL pattern.

I am considering the options below.

1.

/domain/v1/relatedProducts/users/{userId}

/domain/v1/relatedProducts/products/{productId}

2.

/domain/v1/user/{userId}/relatedProducts

/domain/v1/products/{productId}/relatedProducts

3. Please advise other URL patterns.


Solution

  • the products are related to a user, so you should select user first, then list all products. so it should be like

    /domain/v1/users/{userId}/products
    

    notice that i used users not user and products not relatedProducts

    /domain/v1/users/{userId}/products/{productId}
    

    also note, there is no thing wrong with v1 you can keep it or remove it, some of major companies use the version part.

    you can follow some best Practices to URL pattern

    1. Use nouns but no verbs
    2. Use plural nouns
    3. Use sub-resources for relations

    you can find more helpful details at rest api tutorial Resource Naming