REST APIs (Representational State Transfer Application Programming Interfaces) are widely used for building networked applications. This article will help you understand how to work with REST APIs in JavaScript, covering both client-side and server-side implementations.
A REST API allows clients (such as browsers or mobile apps) to communicate with servers to fetch or manipulate data. It follows a stateless architecture using standard HTTP methods.
For Client-Side:
For Server-Side:
JavaScript provides the fetch() API and third-party libraries like axios to interact with REST APIs.
Here’s how to retrieve data from a REST API.
// Fetch data from an API const fetchUsers = async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/users'); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const users = await response.json(); // Parse JSON data console.log(users); } catch (error) { console.error('Error fetching users:', error); } }; fetchUsers();
To create a new resource, use the POST method with the fetch() API.
const createUser = async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/users', { method: 'POST', // HTTP method headers: { 'Content-Type': 'application/json', // Specify JSON format }, body: JSON.stringify({ // Convert JavaScript object to JSON name: 'Jane Doe', email: 'jane.doe@example.com', }), }); const newUser = await response.json(); // Parse JSON response console.log(newUser); } catch (error) { console.error('Error creating user:', error); } }; createUser();
On the backend, Node.js with the Express framework is commonly used to build REST APIs.
// Fetch data from an API const fetchUsers = async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/users'); if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } const users = await response.json(); // Parse JSON data console.log(users); } catch (error) { console.error('Error fetching users:', error); } }; fetchUsers();
Here’s an example of a basic REST API server.
const createUser = async () => { try { const response = await fetch('https://jsonplaceholder.typicode.com/users', { method: 'POST', // HTTP method headers: { 'Content-Type': 'application/json', // Specify JSON format }, body: JSON.stringify({ // Convert JavaScript object to JSON name: 'Jane Doe', email: 'jane.doe@example.com', }), }); const newUser = await response.json(); // Parse JSON response console.log(newUser); } catch (error) { console.error('Error creating user:', error); } }; createUser();
You can test your API using tools like Postman or command-line utilities like curl.
mkdir rest-api-demo cd rest-api-demo npm init -y npm install express
my working code repo
REST APIs are a cornerstone of modern web development. By learning to interact with REST APIs in JavaScript, both on the client and server sides, you’ll gain a powerful skill set for building and integrating applications. Practice is key—start by consuming public APIs and then build your own API using Node.js and Express.
Feel free to ask questions or seek clarifications on any part of this guide!
The above is the detailed content of Learning REST APIs in JavaScript. For more information, please follow other related articles on the PHP Chinese website!