Deno API Server how to get Request body by oak

Taka
3 min readApr 10, 2021

Today, I'm going to share how to get the request body in Deno API Server by oak router module.

Editor

VSCode

Version Infomation
deno 1.8.2 (release, x86_64-apple-darwin)
v8 9.0.257.3
typescript 4.2.2

middleware: oak@v6.5.0

Firstly, you need to import the Router module from oak(in this case version 6.5.0). [the bellow line 5].

Also, you can import RouterContext which shows a router context interface detail in VSCode if you are using TypeScript. [the bellow line 9].

Without RouterContext, the router perfectly works. You can also see the type of context in VSCode like this,

Whereas you can see the interface RouterContext in detail by importing RouterContext from oak router.ts.

It's quite useful if you implement your own module extending the original one.

Implementaion Post API

In a router file, you just create a router instance from Router module.

Note that you must export the router object. export default router;.

Then, define each API as you like. The bellow is the easiest example of POST API which gets a request body and returns a response with the body.

Line 27, getting a request body from context. There is not a bodyoptionshere because the content-type is given in the request header so that the content type is automatically detected in Deno server. I show it later.

Line 28, getting a request body by using await. This is a bit tricky point. In this case, the result should be parsed to JSON.

When returning the response, just code context.response.body = {...}. before that, you can also implement context.response.status = Status.ok. But the default status code should be 200 so I didn't do it here.

Request and Response

In the request, you can set a request header content-type for example application/json as well as a request body.

Execute a POST API.

The response should be like this,

The response content-type will be application/json. And the response body is what you return in POST API router.

It’s ALL DONE!!! You complete the POST API implementation!

If you are interested in error handler and logger middleware in Deno API Server, read the below article.

Deno API Server how to code the Middleware

Thank you!

--

--