Learning objectives
After reading this article you will be able to:
- Understand the principles that make an API REST
- Pick the right HTTP method and status code for each operation
- Build and test a minimal REST API in Node.js with curl
On this page
- How does a REST API work?
- What are the principles of REST?
- Which HTTP method should you use for each action?
- How do you design URLs and status codes?
- What does a REST API look like in Node.js?
- When is a REST API not the best choice?
- How do REST, RESTful and related terms differ?
- How to do this on Square Cloud
- FAQs
Almost every app you use talks to a server through an API. The weather app asks for a forecast, a bot dashboard lists servers, a shop's website creates an order. In most cases that conversation follows the REST style.
REST is not a protocol or a library. It is a set of design rules, described by Roy Fielding in his 2000 doctoral dissertation and now applied on top of HTTP. Knowing those rules helps you both consume APIs and design your own.
How does a REST API work?#
The client (an app, a browser, a bot) sends an HTTP request to a URL. The server processes it and returns a response with a status code and, usually, a JSON body.
curl -i https://api.example.com/books/1HTTP/1.1 200 OK
Content-Type: application/json
{"id": 1, "title": "Dom Casmurro"}Three parts of the request matter: the method (what to do), the URL (on which resource) and, sometimes, a body with data. The response returns the status (whether it worked) and the representation of the resource, usually JSON.
What are the principles of REST?#
Fielding describes REST as a set of architectural constraints:
- Client and server are separate: the user interface and the data storage evolve independently.
- Stateless: each request carries everything the server needs, such as the auth token. The server keeps no session between calls.
- Cache: the response says whether it can be reused, which cuts traffic.
- Uniform interface: resources identified by URL and handled through representations, with self-descriptive messages and links between resources (hypermedia).
- Layered system: proxies, CDNs and load balancers can sit between client and server without the client noticing.
- Code on demand (optional): the server may send executable code to the client.
In practice, most "REST" APIs implement the first ideas well and skip hypermedia. That works, and it is what you will see every day.
Which HTTP method should you use for each action?#
Methods are defined in RFC 9110. Two concepts help you choose: a method is safe when it changes nothing on the server, and idempotent when repeating the call has the same effect as calling it once.
| Method | Typical action | Safe | Idempotent |
|---|---|---|---|
| GET | Read a resource or a list | Yes | Yes |
| POST | Create a resource | No | No |
| PUT | Replace a whole resource | No | Yes |
| PATCH | Change part of a resource | No | Not necessarily |
| DELETE | Remove a resource | No | Yes |
Idempotency matters when the network fails. If a DELETE /books/1 times out, you can retry safely. Retrying a POST may create two records.
How do you design URLs and status codes?#
URLs name things, not actions. The method already states the action.
- Good:
GET /books,GET /books/1,POST /books,DELETE /books/1. - Bad:
GET /getBook?id=1,POST /deleteBook.
Use plurals for collections and nest only when the relationship is clear, like /authors/3/books. The most common status codes:
| Code | When to use |
|---|---|
| 200 OK | A read or update that worked |
| 201 Created | A resource was created (send a Location header with the new URL) |
| 204 No Content | It worked and there is no body, common for DELETE |
| 400 Bad Request | Invalid data from the client |
| 401 Unauthorized | Missing or invalid credentials |
| 404 Not Found | The resource does not exist |
| 409 Conflict | Conflict with the current state, such as a duplicate record |
| 500 Internal Server Error | Unexpected server failure |
Returning 200 with {"error": true} in the body is a common mistake: it breaks clients, caches and monitoring tools that look only at the status.
What does a REST API look like in Node.js?#
With a recent Node.js version, install Express 5 and create server.mjs:
npm install express@5import express from "express";
const app = express();
app.use(express.json());
const books = [{ id: 1, title: "Dom Casmurro" }];
let nextId = 2;
app.get("/books", (_req, res) => res.json(books));
app.get("/books/:id", (req, res) => {
const book = books.find((b) => b.id === Number(req.params.id));
if (!book) return res.status(404).json({ error: "Book not found" });
res.json(book);
});
app.post("/books", (req, res) => {
const { title } = req.body ?? {};
if (typeof title !== "string" || title === "") {
return res.status(400).json({ error: "title is required" });
}
const book = { id: nextId++, title };
books.push(book);
res.status(201).location(`/books/${book.id}`).json(book);
});
app.delete("/books/:id", (req, res) => {
const i = books.findIndex((b) => b.id === Number(req.params.id));
if (i === -1) return res.status(404).json({ error: "Book not found" });
books.splice(i, 1);
res.sendStatus(204);
});
app.listen(process.env.PORT ?? 3000);Run it with node server.mjs and test:
curl -i localhost:3000/books/1
curl -i -X POST localhost:3000/books -H "Content-Type: application/json" -d '{"title":"Quincas Borba"}'
curl -i -X DELETE localhost:3000/books/2
curl -i localhost:3000/books/99You should see 200, 201, 204 and 404. Data lives in memory and disappears on restart; a real API needs a database. Before publishing, go through the API production checklist.
When is a REST API not the best choice?#
REST works well for request and response operations on resources. It struggles elsewhere:
- Real time: chat, games and live prices need an open connection. See what a WebSocket is.
- Screens that need data from many resources: chaining many calls makes the screen slow, and GraphQL lets you ask for everything at once.
- Actions that are not CRUD: "approve order" does not always fit a resource. A
POST /orders/5/approvalusually does the job.
There is no universal winner. REST is the most common choice because it is simple, uses what HTTP already offers and any language can consume it.
How do REST, RESTful and related terms differ?#
- RESTful: an API that follows the REST style.
- HTTP API: a more neutral term, used when the API runs over HTTP but does not follow every constraint.
- RPC: remote function calls, like
POST /createOrder. Actions instead of resources. - Webhook: the reverse direction, where the server calls a URL of yours when something happens.
To put yours online, see how to host an API.
How to do this on Square Cloud#
A REST API is an application that listens on a port and answers HTTP requests, so the example above runs like any Node.js app. You deploy by uploading a ZIP in the dashboard, with the CLI, through GitHub or with the VS Code extension, and every web application gets a *.squareweb.app subdomain with HTTPS.
The squarecloud.app configuration file is optional: the dashboard generates it on deploy, with runtime, memory and main file. A web application needs at least 512 MB from your plan's RAM. There are runtimes for Node.js, Python, Go, Java, PHP and more. Every plan includes traffic with no bandwidth or per-request charges (fair use policy), DDoS protection and a WAF. If your API needs a database, hosting for PostgreSQL, MySQL, MongoDB and Redis starts on the Standard plan.
Square Cloud itself has a REST API (api.squarecloud.app/v2), with official SDKs in JavaScript/TypeScript, Python and Go. To publish yours, see the API hosting page.
API hosting
APIs in always-on containers, with no cold starts
FAQs
What is the difference between an API and a REST API?
An API is any interface that lets one program talk to another. A REST API is a specific kind that uses HTTP, URLs for resources and stateless requests.
Are REST and RESTful APIs the same thing?
In practice, yes. RESTful is just the adjective for an API that follows the REST style. Many APIs called REST follow only part of the rules.
Does REST always use JSON?
No. JSON is the most common format, but REST does not require one. Client and server agree on the format through the Accept header (what the client can receive) and the Content-Type header (the format being sent).
What is the difference between REST and GraphQL?
REST has many URLs, one per resource, and the server decides the response shape. GraphQL has a single endpoint and the client chooses which fields to receive.
Does a REST API need HTTPS?
If it carries tokens or user data, yes. Without HTTPS, credentials and data travel in plain text and can be read along the way.
More in APIs
See all 15 articles- How to host an APIHosting an API means running its HTTP server around the clock at a public address with HTTPS. Step-by-step with Node.js and Python, testing and common errors.
- How to host a Node.js appTo host a Node.js app, prepare package.json, read the port and secrets from the environment, pick an LTS version and run it with node. Step-by-step guide.
- How to host a FastAPI, Flask or Django appTo host a FastAPI, Flask or Django app, run it with a production server (Uvicorn or Gunicorn) on 0.0.0.0. Commands, Django settings and common errors included.
- How to host a Python app or scriptTo host a Python app or script, pin the version, isolate dependencies in a venv, read secrets from the environment and handle SIGTERM. Step-by-step guide.