HTTP Methods in NextJS

HTTP Methods in NextJS

Every website we visit often has its own API, including popular platforms like Twitter. Let's take Twitter as an example. When we search for a user, such as Saurav_Pant_, Twitter utilizes its REST API to handle our request. The API acts as a bridge between the website and its database, processing our search query and fetching the relevant user information. The response from the API is usually in a format called JSON, which is a structured way of organizing data. On the client side, which can be a web browser or an app, the JSON data is processed and presented in a user-friendly manner, such as showing the user's profile information or their recent tweets.

Built-in REST API

Next.js lets you create API routes right inside the application as a serverless function. No need to set up a Node.js server. Just create a JavaScript file inside any folder and put the name of the file is route.ts . The name of the folder will act as the API endpoint. If you want to create nested API routes, create a folder inside the folder
if you want to see its illustrations check the second blog of the series.

To create endpoints, we have four main HTTP methods:

  1. GET: Used to retrieve data from the server. It's like asking for information. For example, fetching a user's Twitter profile details.

  2. POST: Used to send data to the server. It's like submitting a form for a survey. For example, creating a new user account.

  3. PUT: Used to update existing data on the server. It's like editing information. For example, updating a user's profile.

  4. DELETE: Used to remove data from the server. It's like deleting something. For example, deleting a user's account.

So let's first understand the GET Method

Here's how you can create a GET method in NextJS
now if you go to the endpoint you get the JSON, which I put on the image.

Now understand the POST Method

Here's how you can create a POST method in NextJS, In postman you can check this

In this blog, we've covered GET and POST requests. Stay tuned for the next installment in this series, where we'll explore PUT and DELETE as we work on an exciting project