NodJS | Tutorial 2 | Creating your first POST API endpoint

  Welcome to CCP !

Lets get started,


Now, here I am again with yet another article on NodeJS,

So, LETS get RIGHT into IT !


Today, we are going to make our first POST API endpoint,

Hey ! what is a POST endpoint ?

A POST endpoint is a place where we can SEND data to our server,
Till now, we were just requesting data from the server and it was sending us some string, A JSON object [{name: "XYZ", age: 12 ...}] or any other data,

But now we will be TAKING data sent from our request and processing it

How amazing is that !

Now, have a look at this image:


This is how we define a POST endpoint,
It is all same with GET endpoint just we can access the data sent,

Now, go to your browser and type:
http://localhost:<your-given-port>/
In my case, it is: http://localhost:3000/

What do you see ?
A message like this ?


And, your console is empty except for the message "Server started"

Wait, wait, wait  ! before you leave this site in anger,
I just want to tell you that you are doing good and its not your fault or anyone else's

Every time you open a site via a browser,
it by default sends GET request at the URL
you visit and thus the server responded with the code block written under GET endpoint block

Now, we can't change this behavior of the browser but we can install a special, powerful, and quite a popular tool just made for testing server endpoints -- POSTMAN (download here)

This tool helps us to send GET/POST requests to API's out there and fetch/send data to them

It looks something like this:


And, to send this request, we have to press the Send button

Press the
Send button,
What do you see ?

Wow ! that was CLEAN !

Now, lets send some data to our API using postman !

Choose POST from the dropdown:


Now, go to the body section of the request here:


Enter data in the JSON format and press Send:


Yay ! we have a message from the server:
Data successfully received !

Lets check if the server has printed the data in the console or not as we coded it to


Wait, what ?
Why is it showing undefined ?

We have to define a middleware for communication,

Now, what on Earth is this middleware ?

Till now we were just sending texts, and thus the middleware was a text by default,
But, when we sent a JSON object, the server freaked out and saw a JSON in place of a text.
This is why it refused to take it and the request body turned out to be
null

Lets define it boyz !..... And girlz !


Lets again make the same POST request,

Now, what you see in console ?


Yay ! It worked !

Pro tip:
You can also send JSON formatted data now instead of sending those text messages from the server to client

Now, I leave all on you how you handle this new skillset of yours !

Till then...

I'll see YOU. in the NEXT. TUTORIAL !

Comments