| Semester_4 |
|---|
| 01_Introduction |
| 02_DeployAzure |
| 03_JSBasic |
| 04_OOP |
| 05_GET |
| 06_POST |
| 07_PUT |
| 08_PATCH |
| 09_DELETE |
| 10_FrontendTable |
| 11_FrontendAdd |
| 12_FrontendDelete |
| 13_FrontendEdit |
| 14_Database |
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/studentsBody
{
"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). |
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"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:
nameandcourse.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. returnStops 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.lengthChecks 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 + 1If the array is not empty, get the last student’s ID and add 1 to it. 1If 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 constDeclares a constant variable — newStudentcannot be reassigned later.newStudentThe name of the variable that will store the new student’s data. { ... }Creates a JavaScript object with properties (key–value pairs). id: newIdThe property idis assigned the value of the variablenewId.nameShorthand for name: name— it takes the value from the variablename.courseShorthand for course: course— it takes the value from the variablecourse.Same:
const newStudent = { id: newId, name: name, course: course };
students.push(newStudent);
Part Meaning studentsThis 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. newStudentThe object you want to add — for example, { id: 3, name: "Thomas", course: "Informatics" }.It adds the new student object (
newStudent) to thestudentsarray.
res.status(201).json(newStudent);
Part Meaning resThe 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 newStudentas a JSON-formatted response body.It sends a 201 Created response with the newly created student object in JSON format.
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:3000curl 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" }Do not forget to commit and push your work.
Deploy the app.
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"}