API Explanations
API Explanations
Let's break down APIs in the backend using JavaScript from the
ground up.
Imagine you go to a restaurant. You don't go into the kitchen and cook your
own food, right? You look at the menu, tell the waiter what you want, and the
waiter brings it to your table.
* You (the customer): This is like the "client" (e.g., your web browser, a
mobile app).
* The Menu: This is like the "API documentation" – it tells you what you can
ask for.
* The Waiter: This is the "API" itself. It takes your request, goes to the
kitchen, gets the food, and brings it back to you.
* The Kitchen: This is the "backend server" where all the work happens (data
storage, logic, etc.).
* Frontend: What the user sees and interacts with (HTML, CSS, JavaScript in
the browser).
The frontend needs to get data from the backend (e.g., a list of products,
user profiles) and send data to the backend (e.g., save a new user, place an
order). APIs are the bridge that enables this communication.
* POST: Send new data to the server to create a resource. (e.g., "Create a
new user with this information.")
* PUT: Update an existing resource with new data. (e.g., "Update the details
of product ID 123.")
* PATCH: Partially update an existing resource. (e.g., "Update only the price
of product ID 123.")
3. URLs/Endpoints
* URL/Endpoint
* HTTP Status Code (e.g., 200 OK, 404 Not Found, 500 Internal Server
Error)
* Headers
JSON is the most common data format for APIs. It's human-readable and easy
for machines to parse. It looks like JavaScript objects:
"id": 1,
"name": "Laptop",
"price": 1200,
"inStock": true
* Install Node.js: If you don't have it, download and install it from the official
Node.js website: https://nodejs.org/
mkdir my-book-api
cd my-book-api
npm init -y
* Install Express.js:
npm install express
Create a file named app.js in your my-book-api folder and add the following
code:
const port = 3000; // Define the port your server will listen on
// This is crucial for handling POST and PUT requests where data is sent as
JSON
app.use(express.json());
let books = [
];
});
const book = books.find(b => b.id === bookId); // Find the book in our
array
if (book) {
} else {
});
const newBook = req.body; // The client sends the new book data in the
request body
if (!newBook.title || !newBook.author) {
newBook.id = newId;
});
bookFound = true;
return book;
});
if (bookFound) {
} else {
});
books = books.filter(book => book.id !== bookId); // Filter out the book to
be deleted
} else {
});
app.listen(port, () => {
console.log(`Book API listening at http://localhost:${port}`);
});
* const port = 3000;: Defines the port number your server will listen on. You
can choose any available port (e.g., 8080, 5000).
* let books = [...]: Our "database" for this simple example is just a JavaScript
array. In a real application, you'd connect to a database like MongoDB,
PostgreSQL, MySQL, etc.
* res (response object): Used to send the HTTP response back to the
client.
* app.get('/books/:id', ...):
* /:id is a route parameter. The colon (:) signifies that id is a placeholder for
a dynamic value.
* req.params.id: How you access the value of the route parameter (e.g., if
the URL is /books/1, req.params.id will be "1"). We use parseInt() to convert it
to a number.
* app.post('/books', ...):
* req.body: Contains the data sent by the client in the request body (thanks
to app.use(express.json())).
* app.put('/books/:id', ...):
* app.delete('/books/:id', ...):
* app.listen(port, () => { ... });: This starts the Express server and makes it
listen for incoming requests on the specified port. The callback function runs
once the server is successfully started.
node app.js
Now that your server is running, you can interact with it.
curl http://localhost:3000/books
Expected output:
curl http://localhost:3000/books/1
Expected output:
(If you then GET /books, you'll see the new book.)
Expected output:
(If you then GET /books, you'll see "Pride and Prejudice" is gone.)
* Open Postman.
* Click "Send".
* Go to the "Body" tab, select "raw", and choose "JSON" from the
dropdown.
* Enter your JSON data (e.g., {"title": "New Book", "author": "Someone"}).
* Click "Send".
* Repeat for PUT and DELETE, adjusting the method, URL (with ID), and body
as needed.
This is just the beginning! A real-world backend API involves much more:
* Request includes: HTTP Method (GET, POST, etc.), URL, Headers, Body (for
POST/PUT).
* Express routes the request to the appropriate route handler based on the
method and URL.
* Route Handler
* Prepares a response.
* Response is sent back to the client, including: HTTP Status Code, Headers,
Body (often JSON data).
* Client (Frontend) receives the response and uses the data to update the UI
or perform other actions.
* Menu (API Definition): It defines what actions you can perform and how to
ask for them. For a software system, this means specifying what data you
can get, what data you can send, and in what format.
* Kitchen (Backend Server): This is where the work gets done – data is
processed, retrieved, or stored.
The website can’t directly talk to the database. That would be a security
nightmare and incredibly complex. This is where the backend with its APIs
comes in:
* The backend acts as a secure intermediary between your frontend and
your database.
* It exposes APIs that the frontend can call to, for example:
* Process an order.
The backend handles the logic, talks to the database, performs calculations,
and then sends back the requested data (or a confirmation of an action) to
the frontend.
* Same language for frontend and backend: If you know JavaScript for the
frontend, you can use it for the backend too, reducing the learning curve.
We’ll create a very basic API that manages a list of “books.” You’ll be able to:
* Postman or a similar API testing tool (optional but very helpful): This allows
you to send requests to your API and see the responses easily. You can
download it from postman.com/downloads.
Cd my-book-api
Npm init -y
The -y flag answers “yes” to all the default questions, making it quicker.
Now, your package.json file should look something like this (the version
numbers might differ):
“name”: “my-book-api”,
“version”: “1.0.0”,
“description”: “”,
“main”: “index.js”,
“scripts”: {
“test”: “echo \”Error: no test specified\” && exit 1”
},
“keywords”: [],
“author”: “”,
“license”: “ISC”,
“dependencies”: {
“express”: “^4.19.2”
Create a new file named index.js in your my-book-api folder. This will be the
main file for our backend server.
// index.js
// When a frontend sends data (e.g., a new book), it’s often in JSON format.
// This line tells Express to automatically parse that JSON into a JavaScript
object
App.use(express.json());
// 5. Our “Database” (for this simple example, it’s just an array in memory)
Let books = [
];
// This defines a route that responds to HTTP GET requests to the ‘/books’
path.
Res.json(books);
});
// 7. GET /books/:id – Get a single book by ID
// The ‘:id’ is a route parameter. It means whatever comes after /books/ will
be captured
If (book) {
Res.json(book);
} else {
});
// This route handles HTTP POST requests. POST requests are typically used
to create new resources.
If (!newBook.title || !newBook.author) {
newBook.id = newId;
Books.push(newBook);
// Send back the newly created book with a 201 Created status
Res.status(201).json(newBook);
});
App.listen(PORT, () => {
Console.log(‘API Endpoints:’);
Console.log(`- GET http://localhost:${PORT}/books`);
});
Node index.js
API Endpoints:
- GET http://localhost:3000/books
- GET http://localhost:3000/books/:id
- POST http://localhost:3000/books
Your API server is now up and running! It’s listening for requests on port
3000 of your local machine.
Now, let’s use a web browser or Postman to interact with our API.
* Open Postman.
* Click Send.
* Click Send.
* You’ll see the JSON response for “The Hitchhiker’s Guide to the Galaxy”.
* Click Send.
* You should get a 201 Created status and the newly added book, including
its generated id:
“id”: 4
Let’s revisit the index.js file and break down each part:
// 4. Middleware: app.use(express.json());
// This is crucial! When your frontend sends data (especially with POST or
PUT requests),
// it’s typically in JSON format. This line tells Express to automatically parse
// that JSON string from the request body into a JavaScript object. Without
this,
// For simplicity, we’re using a simple JavaScript array to store our books.
// This data is *volatile* - it disappears when you stop and restart your server.
// - MongoDB (NoSQL)
// - PostgreSQL (SQL)
// - MySQL (SQL)
// (e.g., ‘mongoose’ for MongoDB, ‘pg’ for PostgreSQL) and writing code to
// This includes headers, URL parameters, query strings, and the request
body (if any).
// - `res` (Response object): Used to send back the HTTP response to the
client.
Res.json(books);
});
If (book) {
} else {
// Common codes:
});
// `req.body`: This is where the data sent by the client (e.g., the new book’s
title and author)
If (!newBook.title || !newBook.author) {
newBook.id = newId;
books.push(newBook);
Res.status(201).json(newBook);
// Send back the newly created book object with a 201 status code.
});
// 9. Start the server
App.listen(PORT, () => {
// `app.listen()`: This method starts the Express server and makes it listen
// The callback function `() => { … }` runs once the server has successfully
started.
});
This is just the tip of the iceberg! Here are crucial concepts you’ll encounter
as you progress:
* GET: Retrieve data (e.g., get a list of products, get a specific user).
* POST: Create new data (e.g., create a new user, submit an order).
* Validation: Ensuring that the data received from the client is valid and
meets your requirements before processing it (e.g., checking if an email
address is in the correct format). Libraries like joi or express-validator are
common.
* Deployment: Getting your API server online so others can access it. This
involves services like Heroku, Vercel, AWS, Google Cloud, DigitalOcean, etc.
* Testing: Writing automated tests for your API endpoints to ensure they
work as expected.
You’ve built your first basic API! This is a fantastic start. Keep exploring, keep
building, and don’t be afraid to experiment. Happy coding!
Difference between GET & POST
requests in an API
It’s crucial to differentiate between GET and POST requests when designing
your backend API because it dictates how clients interact with your server
and ensures your application is robust, secure, and semantically correct.
Use GET requests when you want to retrieve (read) data from the server
without causing any side effects (i.e., without changing the server’s state).
Characteristics of GET:
* Idempotent: Making the same GET request multiple times will have the
same effect as making it once (it will return the same data).
* Can be bookmarked.
Use POST requests when you want to send data to the server to create a new
resource or to perform an operation that has side effects (i.e., changes the
server’s state).
Characteristics of POST:
* Not Idempotent: Making the same POST request multiple times will
typically create multiple new resources.
* Placing an order.
* Uploading an image.
* Logging a user in (though sometimes POST is used for login, it’s generally
considered best practice for changing state like user session).
Let’s design a simple backend API for a blog. This project will clearly
demonstrate when to use GET and POST.
Core Entities:
API Endpoints:
* Endpoint: /api/posts
* Method: GET
* Example Usage: When a user clicks on an article title to read its full
content.
* Endpoint: /api/posts/:id/comments
* Method: GET
* Endpoint: /api/posts
* Method: POST
* Method: POST
* GET /api/posts and /api/posts/:id are perfect for retrieval. They don’t
change anything on the server. You can refresh the page, share the URL, or
bookmark it, and the data remains consistent without unintended side
effects.
* POST /api/posts is for creating a new resource. Each time you send a POST
request with new post data, you intend to add a new record.
This blog API example provides a clear and practical illustration of how GET
and POST requests are used for their distinct purposes in a real-world
backend project.
Here are the specific methods or scenarios that typically require a POST
request:
* This is the most common and fundamental use case for POST. When a
client wants to add a new entity to your database or system, a POST request
is used.
* Examples:
* Whenever a user fills out a web form (e.g., registration, contact, survey)
and submits it, the data is typically sent to the server via a POST request.
This is because form submissions usually lead to the creation or modification
of data on the server.
* Examples:
* File Uploads:
* When a client needs to send a file (image, document, video, etc.) to the
server, a POST request is used. The file data is sent in the request body,
often using multipart/form-data encoding.
* Examples:
* POST requests are used for actions that are not idempotent, meaning
that performing the same request multiple times will have different (and
often undesirable) effects. This usually implies a change in state on the
server.
* Examples:
* Logging in/out: While often a GET for logout, login often involves POST
to send credentials securely and create a session.
* While technically not a strict rule about method requiring POST, it’s a
best practice to use POST when sending sensitive data (like passwords,
credit card numbers) or very large amounts of data.
* Size Limits: URLs have practical length limits (though not strictly defined
by HTTP, browsers and servers impose them). POST requests have no such
practical limits on the body size.
While POST is primarily for creating resources, you might sometimes see it
used for complex search queries or “action-based” endpoints where the
query parameters for a GET request would be too long, complex, or sensitive.
In these cases, the semantics might lean towards “retrieving” data, but the
practicalities (data size, complexity, or sensitivity) dictate using POST to put
the query payload in the request body. However, strictly speaking, RESTful
principles would encourage using GET for retrieval if possible.
In essence, if your API call is going to alter the state of the server or create
something new, a POST request is almost always the correct HTTP method to
use.