Handle JSON request bodies and send JSON responses from a Node.js server using ReasonML

Murphy Randle
InstructorMurphy Randle

Share this video with your friends

Send Tweet
Published 4 years ago
Updated 3 years ago

This lesson shows how the Serbet server library for ReasonML and Node.js makes handling JSON request bodies, and responding with JSON request bodies a simple task.

Instructor: [0:00] Here I've got a basic server that responds to a get request with a "Hello World!" message, but let's say I want to do something a little more complex and actually deal with JSON. Module json endpoint, this is just the name of my module, it's there for me to remember what this does, = app.handle.

[0:19] Now we're going to use a fancy little shortcut called HandleJson. This is nice if you're doing a brand-new server and you don't have to conform to old APIs and do stuff in weird ways. If you're just starting out with a server that can take json and respond with json, this is a really nifty way to go.

[0:36] Let's add our verb, let verb equal, and let's do a post, and let's let the path be "/hello/json". Now I've got to specify a body type, so @decco.decode type body =, now let's have the body have the name in it, name: strong, and we also need to specify a response type.

@[0:58] decco.encode, because we're going to be encoding the response, type response =, and let's say there's a message on the response, and that's a string. Now we need to add the handler. Let handler =, now instead of just the request, I'm actually going to take in the body and then the request, and then respond.

[1:20] The funny thing is now that I have the body, I don't actually need the request. I'm going to put an underscore in front of it so the compiler doesn't get angry with me. All right, so now let's respond. This is a little different than the above, where I said OK string, because since this endpoint knows that I'm going to be handing back JSON and that I've specified a response type, I can just return a promise of the response type.

[1:40] I'm going to initialize a record with a field message, and that's going to be "Hello there, " ++ body.name and then I'm going to make it async, and all of our compiler warnings go away. Now you can rerun the server and try it out. I've got a handy little utility called HTTPie installed for doing http request from the command list.

[2:01] Let's try that now. http POST locahost:1337/hello/json and you can specify a JSON body using this tool, just by passing name=superface it's going to take care of actually building that into a JSON body for me. Let's see what happens.

[2:20] All right, so you see the server took that JSON body in, parsed it, and then responded with more JSON, "message": "Hello there, superface". This is how you very quickly make an endpoint that can take in, validate, parse JSON, and return other JSON.