search
HomeWeb Front-endJS TutorialCode Your First API With Node.js and Express: Understanding REST APIs

Code Your First API With Node.js and Express: Understanding REST APIs

Introduction to REST and RESTful APIs

In modern web development, you must often encounter terms such as REST and API. If you have heard of these terms or used APIs but don't fully understand how they work or how to build your own API, this tutorial series is right for you.

This tutorial series will first overview of REST principles and concepts. We will then create a complete API that runs on the Node.js Express server and connects to the MySQL database. After completing this series of tutorials, you should be able to build your own API with confidence or dig into documentation for existing APIs.

Prerequisites

To make the most of this tutorial, you should have some basic command line knowledge, basic JavaScript knowledge, and install Node.js globally.

What are REST and RESTful APIs?

Declarative State Transfer ( REST ) ​​describes an architectural style of a Web service. REST contains a set of standards or constraints for sharing data between different systems. The system that implements REST is called RESTful. REST is an abstract concept, not a language, framework, or software type.

A loose analogy about REST is: keeping vinyl record collections and using streaming music services. For physical vinyl record collections, each record must be copied in full in order to share and distribute copies. However, for streaming services, the same music can be shared permanently by reference to certain data, such as song titles. In this case, streaming music is a RESTful service, while vinyl record collection is a non-RESTful service.

API is an application programming interface, which is an interface that allows software programs to communicate with each other. The RESTful API is just an API that follows REST principles and constraints. In the Web API, the server receives the request through the URL endpoint and returns a response , which is usually data in JSON format.

REST Principle

Six guiding constraints define the REST architecture as follows:

  1. Unified interface : The interfaces of components must be the same. This means using the URI standard to identify resources—in other words, paths that can be entered into the browser's address bar.
  2. Client-Server : There is a separation of concerns between the server (store and operate data) and the client (request and display response).
  3. Stateless interaction : All information about each request is contained in each individual request and does not depend on the session state.
  4. Cacheable : Clients and servers can cache resources.
  5. Hierarchical system : The client can connect to the final server, or to the intermediate layer, such as a load balancer.
  6. On-demand code (optional) : The client can download the code, thereby reducing external visibility.

Requests and responses

You may already be familiar with all websites' URLs starting with https (safe version). Hypertext Transfer Protocol ( HTTP ) is a method of communication between clients and servers on the Internet.

We most obviously see it in the browser's URL bar, but HTTP can not only be used to request websites from the server. When you access a URL on the web, you are actually performing GET and other types of requests.

HTTP makes a request by opening a TCP (Transport Control Protocol) connection to the server port (http, https), and the listening server returns the status and body.

The request must contain URL, method, header information, and body.

Request method

There are four main HTTP methods, also known as HTTP verbs, which are commonly used to interact with Web APIs. These methods define the actions to be performed on any given resource.

The HTTP request method roughly corresponds to the CRUD example, which represents creation, update, read, and delete . Although CRUD refers to the functions used in database operations, we can apply these design principles to HTTP verbs in the RESTful API.

 <code>curl -i https://www.google.com</code>

Google's server will return the following:

 <code>HTTP/2 200 date: Sun, 21 Aug 2022 19:06:22 GMT expires: -1 cache-control: private, max-age=0 content-type: text/html; charset=ISO-8859-1 ...</code>

We can see the 200 status code, as well as the version of HTTP (this will be HTTP/1.1, HTTP/2 or HTTP/3).

Since this particular request returns a website, it is text/html. In the RESTful API, you may see a curl request to Google (not including google.com) returning a 301 response indicating that the resource should be redirected.

REST API Endpoint

When an API is created on the server, the data it contains can be accessed through the endpoint. An endpoint is a URL that can accept and process requests for POST, DELETE requests.

The API URL will consist of the root, path, and optional query string.

  • Root For example, the root of https://www.php.cn/link/9efa87e164995a7743eca9ad63029fa4 may contain protocols, domain names and versions.
  • Path for example /users/5: The only location for a specific resource.
  • Query parameters (optional) such as limit=10, are used to filter the response to contain only ten results.

For example, to get a user with ID 5, we will use /user/5.

REST API Contract

Here are some conventions you should follow when building a RESTful API:

  • Endpoints should not display file extensions : Although the API is most likely to return JSON, the URL should not end in .json.
  • Use nouns instead of verbs : For example, to add a user, we should use the /users endpoint and use the POST request instead of the /users/add endpoint. The API should be developed to be able to handle multiple types of requests to the same URL.
  • Paths are case sensitive and should use lowercase letters and hyphens instead of underscores : for example, /users-list is preferable to /users_list.

All of these conventions are guiding principles because there are no strict REST standards to follow. However, using these guidelines will make your API consistent, familiar, and easy to read and understand.

Alternatives to REST

REST is a great tool, but there are some alternatives that can help in some cases.

SOAP

SOAP (Simple Object Access Protocol) is an API created in 1998 and was very popular before REST. There are some major differences between them. First, SOAP has much stricter restrictions on response formats. Second, SOAP uses XML instead of JSON, which may be useful for legacy applications, but is usually larger and more complex than equivalent JSON. Finally, while SOAP works well with HTTP, it also supports protocols such as SMTP.

GraphQL

GraphQL is a newer API format created by Facebook that aims to reduce the number of HTTP requests needed to get the data by allowing clients to accurately tell the server what data it needs. Instead of using URL paths, GraphQL has a custom syntax to define what data the client needs so that the client gets everything it needs in one request.

For a great introduction to GraphQL, check out this GraphQL tutorial.

in conclusion

In this article, we learn what REST and RESTful APIs are, how HTTP request methods and response code work, the structure of API URLs, and the common RESTful API conventions. In the next tutorial, we will learn how to put all these theories into practice by setting up an Express server with Node.js and building our own API.

This article has been updated and includes Jacob Jackson's contributions. Jacob is a web developer, tech writer, freelancer and open source contributor.

The above is the detailed content of Code Your First API With Node.js and Express: Understanding REST APIs. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment