0

I am building a REST API. To retrieve a specific product, there is an API endpoint:

GET /product/{product-id}

This endpoint returns 200 with the response body. However, currently, I am returning the status 200 with the body as null when product-id does not exist. What should be the response code actually? Is returning 200 is ok?

Example:

product with ID 100, 101, 102, 103 exist is my service.

GET /product/100 -> returns json response with status code as 200
GET /product/101 -> returns json response with status code as 200
GET /product/102 -> returns json response with status code as 200
GET /product/103 -> returns json response with status code as 200

But there is no product with ID 999 in this service. What's the response code?

GET /product/999 -> what should be the response code for this case?

This is a very fundamental question for building a basic REST CRUD application. And now I see I don't understand what should be the response code!

I would appreciate it if someone can guide me what is the best practice considering the best practices for REST API design.

Exploring
  • 2,493
  • 11
  • 56
  • 97
  • @pzaenger it does not answer the question. That question was for a user-facing page and this is related to what is the best practice for a REST API. – Exploring Dec 30 '20 at 20:58
  • 2
    I think, returning a `404` is suitable. See e.g. [this question](https://stackoverflow.com/questions/25868596/restful-ajax-which-http-status-code-for-item-not-found); or [this](https://www.restapitutorial.com/lessons/httpmethods.html) for `GET` a specific Item (e.g. `/customers/{id})`: _`200` (OK), single customer. `404` (Not Found), if ID not found or invalid._ – pzaenger Dec 30 '20 at 21:04
  • @pzaenger again its a user facing app and `404` makes sense. But I am wondering what should I do considering best practices for REST API design. – Exploring Dec 30 '20 at 21:08
  • Both links are about REST and the [last one](https://www.restapitutorial.com/lessons/httpmethods.html) is explicit about CRUD operations. – pzaenger Dec 30 '20 at 21:19
  • REST = HTTP, user facing pages are HTTP. In HTTP you return 404 if a resource does not exist. – Evert Dec 30 '20 at 21:35

0 Answers0