Hono Tutorial Pt. 4

Sep 11, 2024

As the adjustment for the credentials are done in the previous article, we are now ready to create the CRUD end-points for the Contact resource. But, before that, I would like to cover a few methods that are needed in CRUD end-points such as fetching value(s) from dynamic params, reading request body, fetching value(s) from query string, and so on.

Let’s start with the dynamic params for this end-point: /contacts/:id. To fetch the id, we need to use c.req.param() method. This method returns a param object that we can de-structure to get id.

const { id } = c.req.param();

// OR

const id = c.req.param('id');

Next, to read the request body, c.req.json() method is used. Again, this method returns a request body object that we can de-structure to get the given field. In the case of contacts end-point, it might be firstName and lastName.

const { firstName, lastName } = c.req.json();

// OR

const firstName = c.req.json('firstName');
const lastName = c.req.json('lastName');

c.req.json() method is useful when you’re reading a request body with type application/json. But, if the request is in plaintext as text/plain type, then need to use c.req.text() or if request body type is blob, then need to use c.req.blob(). There are a couple of methods available within the c.req object based on the type of data you get in the request body. Refer the HonoRequest documentation for the more details.

Finally, to read the data from the querystring, c.req.query() method is used. This method returns a querystring object that we can de-structure to get the given querystring.

const { limit, offset } = c.req.query();

// OR

const limit = c.req.query('limit');
const offset = c.req.query('offset');

We are now ready to build the CRUD end-points for the Contacts resource.

Tags: hono