TL;DR: This guide breaks down how REST APIs act as a secure middleman between client applications and databases using a simple restaurant analogy. You will learn how APIs use standard HTTP methods like GET, POST, PUT, and DELETE to process JSON data, and see how authorization headers protect your database from direct, insecure client access.
⚡ Key Takeaways
- Never connect a client app directly to a database (e.g., using
database.connect()in frontend code); always route requests through an API to prevent unauthorized data deletion. - Map your application's CRUD operations to standard HTTP methods: use
GETto retrieve data,POSTto create,PUT/PATCHto update, andDELETEto remove. - Format data exchanges between the client and server using JSON payloads for both the request (the "order") and the response (the "delivery").
- Use the
Accept: application/jsonheader in your raw HTTP requests to explicitly tell the server how to format its response data. - Secure your API endpoints by requiring an
Authorization: Bearer my_secret_tokenheader to verify client permissions before allowing the API to interact with the database.
You have a brilliant idea for a startup. You want to build a mobile app and a website where users can book fitness classes. You talk to a developer, and within five minutes, they say: "We'll need to build a backend REST API to connect the mobile app to the database."
If you aren't a software engineer, this sentence probably sounds like a foreign language.
The software world is full of acronyms, but API is arguably the most important one. It is the invisible glue that holds the entire modern internet together. Every time you check the weather on your phone, tap "Like" on a friend's Instagram photo, or pay for a movie ticket online, you are using an API.
In this beginner's guide, we are going to break down exactly what an API is, what makes it a "REST" API, why it matters for your projects, and how to write one from scratch using simple code.
The Problem: How Do Programs Talk to Each Other?
Imagine you have built an iOS app. You also have a database hosted on a server somewhere in the cloud that holds all your user accounts.
Your iOS app cannot just magically reach out across the internet and directly touch the database files. Doing so would be incredibly insecure—anyone could delete your entire database! Furthermore, your mobile app is likely written in a language like Swift or Dart, while your database speaks a query language like SQL. They cannot understand each other directly.
To solve this, developers write a middleman application.
// ❌ The WRONG way (Never do this)
// A client app directly trying to delete a user from a database
database.connect("admin_password");
database.deleteUser("John Doe");
// ✅ The RIGHT way
// The client app asks the API to do it securely via an HTTP request
fetch("https://api.myapp.com/users/johndoe", { method: "DELETE" });
This secure, controllable middleman is the API.
What Exactly is an API? The Restaurant Analogy
API stands for Application Programming Interface.
Simply put, an API is a set of rules that allows one piece of software to talk to another.
To understand this, let’s look at a classic real-world analogy: Dining at a restaurant.
- The Client (You): You sit at a table looking at a menu. You know what you want to eat, but you aren't allowed to walk into the kitchen and cook it yourself.
- The Server/Database (The Kitchen): The kitchen has all the ingredients and knows how to prepare the food, but the chefs don't take orders directly from the customers.
- The API (The Waiter): The waiter is the middleman. You tell the waiter what you want. The waiter takes your order to the kitchen, waits for the chefs to cook it, and then delivers the food back to your table.
In the software world, your mobile app is the customer. The database is the kitchen. The API is the waiter handling requests and returning responses.
Here is what that "order" looks like when two computers talk to each other using data instead of spoken words:
The Request (The Order)
{
"customer": "Table 5",
"action": "order",
"item": "Cheeseburger",
"modifications": "No onions"
}
The Response (The Food Delivery)
{
"status": "success",
"food": "🍔 Cheeseburger without onions",
"estimatedTime": "15 minutes"
}
What Makes it a "REST" API?
If an API is the waiter, REST is the specific etiquette or set of rules the waiter must follow.
REST stands for Representational State Transfer. You don't need to memorize that phrase. What you do need to know is that REST is an agreed-upon architectural standard for how web APIs should be structured so that developers all over the world can easily understand them.
A REST API relies on standard HTTP Methods (also called verbs) to tell the server what action to perform. Think of these as the fundamental actions of your application:
- GET: Retrieve data (e.g., Reading the restaurant menu).
- POST: Create new data (e.g., Placing a brand new order).
- PUT / PATCH: Update existing data (e.g., Changing your order from a burger to a salad).
- DELETE: Remove data (e.g., Canceling your order).
When a client wants to communicate with a REST API, it sends an HTTP request over the internet that looks like this raw text block:
GET /users/123 HTTP/1.1
Host: api.softwarecrafting.in
Authorization: Bearer my_secret_token
Accept: application/json
This simple text block tells the server: "Hey, I am looking for the user with the ID of 123. Here is my secret password to prove I am allowed to see this, and please give me the answer back in JSON format."
Security Tip: Notice the
Authorizationline above? A good REST API never blindly trusts a request. Just like a bouncer checking IDs, the API verifies if the client is authorized to perform the requested action before it ever touches the database.
Why REST APIs Matter for Real Projects
Why do we go through all the trouble of building APIs? Why not just put all the logic directly inside the mobile app?
Because Separation of Concerns allows you to scale.
If you build a tight, well-structured API, you only have to write your business logic and database connections once. Then, you can connect endless different user interfaces to that single source of truth.
When building platforms for our past projects across logistics and healthcare, we never hardcode backend logic into the frontends. We build one central REST API. Then:
- The iOS app consumes the API.
- The Android app consumes the API.
- The web dashboard consumes the API.
Here is a conceptual configuration showing how multiple frontends point to one single backend URL:
// frontend-web/config.js
export const API_URL = "https://api.ourstartup.com/v1";
// frontend-ios/config.swift
let apiUrl = "https://api.ourstartup.com/v1"
// frontend-android/config.kt
val apiUrl = "https://api.ourstartup.com/v1"
If you ever need to change how a user's password is encrypted, you only change the API code. All three frontends instantly benefit from the update without requiring users to download a new version of their apps.
If you are a non-technical founder planning a software product, ensuring you have a robust custom backend architecture that exposes a clean REST API is the single most important technical decision you will make. It guarantees your software can grow in the future.
Understanding the Language: JSON and Endpoints
Before we write our own code, we need to define two more crucial terms: Endpoints and JSON.
Endpoints
An Endpoint is a specific URL where an API can be accessed. Think of it like a specific department in a large company. If you want billing, you call the billing department. If you want technical support, you call tech support.
https://api.myapp.com/users(Endpoint for user data)https://api.myapp.com/products(Endpoint for product data)
JSON (JavaScript Object Notation)
When the mobile app asks the API for data, the API needs to reply in a format that the mobile app can easily read. Today, almost all modern REST APIs use JSON.
JSON is just plain text structured in a specific way using {} (curly braces) and key-value pairs separated by colons. It is incredibly easy for both humans and machines to parse.
{
"id": 123,
"name": "Sarah Connor",
"email": "sarah@example.com",
"isPremiumMember": true,
"favoriteClasses": ["Yoga", "Boxing"]
}
How to Build a Simple REST API (Real Example)
Let's demystify the magic and actually build a working REST API. We will use Node.js (a runtime that allows us to run JavaScript on a server) and Express (a popular, beginner-friendly framework for creating web servers).
Step 1: Set Up the Project
First, open your computer's terminal (command line) and create a new project.
# Create a new folder
mkdir my-first-api
cd my-first-api
# Initialize a new Node.js project
npm init -y
# Install Express
npm install express
Step 2: Write the API Server Code
Next, create a file named server.js and write the actual API code. Don't worry if you've never coded before; read the comments starting with // to understand what each section does.
// 1. Import the Express tool we just installed
const express = require('express');
// 2. Create a new Express application
const app = express();
// 3. Define the port our server will run on
const PORT = 3000;
// 4. Create a fake database (just an array in memory for this example)
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
// 5. Create a GET Endpoint
// When someone visits "http://localhost:3000/api/users", run this function
app.get('/api/users', (req, res) => {
// Respond (res) with the users array formatted as JSON
res.json({
success: true,
data: users
});
});
// 6. Start the server
app.listen(PORT, () => {
console.log(`Server is running! API is ready on http://localhost:${PORT}`);
});
Step 3: Run the API
Back in your terminal, tell Node.js to execute your file:
node server.js
# Output: Server is running! API is ready on http://localhost:3000
Congratulations! You have just created a functioning REST API. It is now running locally on your machine.
Testing Your API: How to Talk to It
Now that the API (the waiter) is standing by, how do we act as the client (the customer) and make an order?
Because it is a simple GET request, you could literally open your web browser and type http://localhost:3000/api/users into the address bar. You would see the JSON text appear right on your screen!
However, developers usually use command-line tools like curl or visual applications like Postman to test APIs. Here is how you would test it using curl in a separate terminal window:
# Send an HTTP request to our new API endpoint
curl http://localhost:3000/api/users
# The API responds with:
# {"success":true,"data":[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]}
Following the Rules: HTTP Status Codes
We missed one final piece of the REST etiquette: Status Codes.
When a waiter brings you your food, they might say, "Here is your order." But if the kitchen is out of burgers, they will come back and say, "Sorry, we are sold out."
APIs do this using standard three-digit numbers called HTTP Status Codes. Every single response from an API must include one.
- 200 OK: The request was successful (Here is your data).
- 201 Created: Data was successfully created (Account registered successfully).
- 400 Bad Request: You sent invalid data (You forgot to include an email address).
- 401 Unauthorized: You aren't logged in (Please provide a password).
- 404 Not Found: The endpoint or data does not exist (That user ID is wrong).
- 500 Internal Server Error: The server crashed (The database went offline).
Let's update our Node.js code to include a route that looks for a specific user by their ID, and returns a 404 Not Found status code if they don't exist.
// Adding a dynamic endpoint looking for a specific ID
app.get('/api/users/:id', (req, res) => {
// Extract the ID from the URL parameters
const userId = parseInt(req.params.id);
// Search our "database" for a user with that ID
const foundUser = users.find(user => user.id === userId);
if (foundUser) {
// Return 200 OK along with the user data
res.status(200).json({ success: true, data: foundUser });
} else {
// Return 404 Not Found and an error message
res.status(404).json({ success: false, message: "User not found in our system." });
}
});
Now, if a mobile app asks for user ID 999, the API cleanly rejects it and tells the app exactly why it failed. The mobile app developers can then program their app to pop up a friendly message on the user's screen saying, "Sorry, we couldn't find that user."
Summary
To recap what we have learned about REST APIs:
- An API is a middleman that lets a client (like an iOS app) talk to a server/database.
- REST is the agreed-upon architectural standard for how those messages should be structured.
- They communicate using HTTP Methods (GET, POST, PUT, DELETE) and Endpoints (specific URLs).
- They exchange data using JSON, a simple, human-readable format.
- They reply with HTTP Status Codes to let the client know if the request succeeded or failed.
By decoupling your application's visible frontend from its hidden backend data processing, you create software that is secure, fast, and ready to scale across any platform.
Need help building this in production?
SoftwareCrafting is a full-stack dev agency — we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.
Get a Free ConsultationFrequently Asked Questions
Why shouldn't a mobile app connect directly to a database?
Connecting a client app directly to a database is highly insecure and could allow malicious users to delete or modify your entire database. Additionally, mobile apps and databases often use different programming languages and cannot communicate directly. Instead, developers use an API as a secure middleman to handle these interactions safely.
What is the difference between an API and a REST API?
An API (Application Programming Interface) is a general set of rules that allows two pieces of software to communicate, acting like a waiter between a customer and a kitchen. A REST API specifically follows the Representational State Transfer architecture, which is an agreed-upon standard for structuring web APIs. REST APIs rely on standard HTTP methods to tell the server exactly what actions to perform.
What are the standard HTTP methods used in a REST API?
REST APIs use specific HTTP verbs to perform fundamental actions on data. The most common methods are GET for retrieving data, POST for creating new data, PUT or PATCH for updating existing data, and DELETE for removing data. These methods ensure developers worldwide can easily understand and interact with the application's backend.
How do REST APIs handle security and user authentication?
A well-designed REST API never blindly trusts an incoming HTTP request. It acts like a bouncer, using headers like Authorization with secret bearer tokens to verify the client's identity. The API ensures the client is fully authorized to perform the requested action before it ever interacts with the database.
How can SoftwareCrafting help me build a custom REST API for my application?
If you need a secure, scalable backend for your mobile app or website, the expert developers at SoftwareCrafting can build a custom REST API tailored to your specific needs. We handle the complex middleman logic, ensuring your client applications communicate safely and efficiently with your database. Partnering with SoftwareCrafting ensures your API follows industry-standard REST architectures and strict security practices.
Does SoftwareCrafting use Node.js to develop backend REST APIs?
Yes, SoftwareCrafting frequently utilizes Node.js to build fast, beginner-friendly, and highly scalable REST APIs from scratch. By leveraging Node.js alongside standard HTTP methods and JSON data formatting, our services provide robust backend systems that seamlessly connect your frontend applications to your cloud databases.
📎 Full Code on GitHub Gist: The complete
api-vs-direct.jsfrom this post is available as a standalone GitHub Gist — copy, fork, or embed it directly.
