> For the complete documentation index, see [llms.txt](https://book.restfulnode.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://book.restfulnode.com/part-3/chapter-7/4-retrieving-a-book-by-id-implementation.md).

# Retrieving A Book By ID - Implementation

## 1 - Route Name

We will first add a route of `GET /api/v1/books/:id`*.*

*File: src/routes/book.route.js*

```javascript
const express = require('express')
const router = express.Router()

const {
  getAllBooks,
  getBookById
} = require('../controllers/book')

router.get('/', getAllBooks)
router.get('/:id', getBookById) // This is our newly added route

module.exports = router
```

Followed by the controller setup.

*File: src/controllers/books/getABookById.js*

```javascript
const catchException = require('../utils/catchExceptions')

const getBookById = catchException(async (req, res, next) => {
  // our code goes here...
})
```

## 2 - Input Request

None.

## 3 - Middleware

None.

## 4 - Validation

None.

## 5 - Domain

The `getById()` method will look this, nice and simple.

*File: src/domain/services/bookRepository.js*

```javascript
// Retrieve - one
const getById = async (id) => {
  return await Model.findById(id)
}
```

Now for us to actually use the `bookRepository` in our `bookService`.

*File: src/domain/services/bookService.js*

```javascript
// Retrieve - one
const getBookById = async (bookId) => {
  const book = await bookRepository.getById(bookId)

  return book
}
```

## 6 - Events

None.

## 7 - Response

But wait! let's not forget the 404 validation we promised.

*File: src/domain/services/bookService.js*

```javascript
// Retrieve - one
const getBookById = async (bookId) => {
  if (!mongoose.Types.ObjectId.isValid(bookId)) {
    // the id is invalid
    throw new ApiException({
      message: `the book with that id: ${bookId} does not exist.`,
      status: 'failed',
      code: 404,
      data: null,
      errors: [`the book with that id: ${bookId} does not exist.`]
    })
  }

  const book = await bookRepository.getById(bookId)

  if (!book) {
    throw new ApiException({
      message: `the book with that id: ${bookId} does not exist.`,
      status: 'failed',
      code: 404,
      data: null,
      errors: [`the book with that id: ${bookId} does not exist.`]
    })
  }

  return book
}
```

As usual, here is our controller. Thanks to us doing the business logic validation in our domain layer, our controller is thin and free of clutter.

*File: src/controllers/book.controller.js*

```javascript
const getBookById = catchException(async (req, res, next) => {
  const book = await bookService.getBookById(req.params.id)

  return res.json(
    globalResponseDTO({
      status: 'success',
      code: 200,
      message: `Book with the specified id.`,
      data: book,
      errors: null
    })
  )
})
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://book.restfulnode.com/part-3/chapter-7/4-retrieving-a-book-by-id-implementation.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
