content

POST

In REST (Representational State Transfer), POST is one of the main HTTP methods — just like GET, PUT, PATCH, and DELETE.

Each method describes what kind of action the client wants the server to perform.

Method Purpose
GET Retrieve data
POST Create new data
PUT Replace existing data
PATCH Update part of existing data
DELETE Remove data

POST = Create a New Resource

When a client sends a POST request, it’s asking the server to add new information.

What Happens

  • The client sends data to the server (using the POST method).

  • The server receives it and creates a new record (e.g., a new student in the database).

  • The server responds with a status code 201 (Created) and returns the newly created object — often with an assigned ID.

Request

POST /api/students

Body

{
  "name": "Thomas",
  "course": "Informatics"
}

Response:

{
  "id": 15,
  "name": "Thomas",
  "course": "Informatics"
}

POST Request Structure (http structure)

POST /api/students HTTP/1.1
Host: example.com
Content-Type: application/json

{
  "name": "Thomas",
  "course": "Informatics"
}
Part Meaning
POST HTTP method — tells the server you want to create something.
/api/students The endpoint (the “place” where new students are created).
Content-Type: application/json Tells the server the request body is JSON.
Body The actual data to be stored (the new student).

Step-by-Step

1. activate Body-Parser

const express = require("express");
const app = express();
// **NEW** activate Body-Parser
app.use(express.json());

This allowes Express to use req.body.

Part Meaning
app Your Express application object (created with const app = express();).
.use() Adds middleware to your app — middleware runs before your routes and can modify the request or response.
express.json() A built-in middleware function in Express that automatically parses JSON data from incoming requests.

If a request has JSON data in its body, automatically read it and convert it into a JavaScript object that I can use.

Without express.json(), you’d have to manually handle raw data — it would just look like unreadable text.

With app.use(express.json()), Express automatically parses that data, and you can access it easily as:

req.body.name    // "Thomas"
req.body.course  // "Informatics"

2. POST-Route hinzufügen

Add below the GET-route (/students/:id) the new route:

// **NEW** add 1 Student
app.post("/students", (req, res) => {
  const { name, course } = req.body;

  // check if the JSON includes name and course 
  if (!name || !course) {
    return res.status(400).json({ error: "Name and course are required!" });
  }

  // Create a new ID (simple add 1 to the last ID in the array)
  const newId = students.length ? students[students.length - 1].id + 1 : 1;

  // Create a new Student
  const newStudent = { id: newId, name, course };
  
  // Add the new Student to the array
  students.push(newStudent);

  // Returns OK and the newStudent as a JSON Object
  res.status(201).json(newStudent);
});

const { name, course } = req.body;

That line uses a JavaScript feature called object destructuring to easily extract data from an object — in this case, from req.body.

It creates two variables: name and course.

Same:

const name = req.body.name;
const course = req.body.course;

if (!name || !course) { return res.status(400).json({ error: "Name and course are required!" }); }

Part Meaning
if (!name \|| !course) Checks if the user forgets to include either the name or the course in the request.
return Stops running the rest of the function — nothing below this line will execute.
res.status(400) Sets the HTTP status code to 400, which means Bad Request — the client sent invalid or incomplete data.
.json({ error: "Name and course are required!" }) Sends a JSON response back to the client with an error message.

const newId = students.length ? students[students.length - 1].id + 1 : 1;

Part Meaning
students.length Checks how many items (students) are in the array.
? ... : ... This is the ternary operator, a short version of an if/else statement.
students[students.length - 1].id + 1 If the array is not empty, get the last student’s ID and add 1 to it.
1 If the array is empty, start with ID = 1.

Same:

let newId;
if (students.length > 0) {
  newId = students[students.length - 1].id + 1;
} else {
  newId = 1;
}

const newStudent = { id: newId, name, course };

Part Meaning
const Declares a constant variable — newStudent cannot be reassigned later.
newStudent The name of the variable that will store the new student’s data.
{ ... } Creates a JavaScript object with properties (key–value pairs).
id: newId The property id is assigned the value of the variable newId.
name Shorthand for name: name — it takes the value from the variable name.
course Shorthand for course: course — it takes the value from the variable course.

Same:

const newStudent = {
  id: newId,
  name: name,
  course: course
};

students.push(newStudent);

Part Meaning
students This is an array that holds all the current student objects. Example: [{ id: 1, name: "Anna" }, { id: 2, name: "Ben" }]
.push() A JavaScript array method that adds a new element to the end of the array.
newStudent The object you want to add — for example, { id: 3, name: "Thomas", course: "Informatics" }.

It adds the new student object (newStudent) to the students array.

res.status(201).json(newStudent);

Part Meaning
res The response object — used by Express to send data back to the client (like Postman, a browser, or another app).
.status(201) Sets the HTTP status code of the response to 201, which means “Created.”
.json(newStudent) Sends the data newStudent as a JSON-formatted response body.

It sends a 201 Created response with the newly created student object in JSON format.


Test

Check:

$ npm run dev

> student@1.0.0 dev
> nodemon server.js

[nodemon] 3.1.10
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,cjs,json
[nodemon] starting `node server.js`
Server running at http://localhost:3000
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Server running at http://localhost:3000

curl Request:

curl -X POST http://localhost:3000/students \
  -H "Content-Type: application/json" \
  -d '{"name":"Katrin","course":"BWL"}'

JSON Response:

{ "id": 11, "name": "Katrin", "course": "BWL" }

GIT

Do not forget to commit and push your work.

Azure

Deploy the app.

001.png

Test the app - just use the Azure URL

$ curl -X POST https://griesmayerstudent-apbdbxe7bwf9cjax.swedencentral-01.azurewebsites.net/students   -H "Content-Type: application/json"   -d '{"name":"Katrin","course":"BWL"}'
{"id":11,"name":"Katrin","course":"BWL"}
002.png