From the course: Master Next.js by Building Scalable Apps with Routing, Databases, and Performance

Unlock this course with a free trial

Join today to access over 25,200 courses taught by industry experts.

API creation for fetching a product by its ID

API creation for fetching a product by its ID

So, now we have completed the interface for the single product. Now we will fetch the product details using its ID. So let's work on the fetching product details API. We will create an API route called slash API slash products slash in the square brackets product ID. Now I will navigate to the API folder and creating a folder called product id inside the products folder. All right now let me create a get method for fetching the product details and it will receive the request as well as the params. Here I will take the try catch block and inside the catch block I will say return next response dot json. In the object, I will say message, something went wrong, error, error.message and the status will be 500. Now I will take a variable to store id inside the try block. I will say const product id is equal to params.productId and will use the db.findUnique method to fetch the product details based on the id. So I will say const product is equal to await db dot product dot find unique. Here…

Contents