Lesson 5

Exploring RESTful APIs in Express.js: A Beginner's Guide

Introduction to API and REST

Welcome to the fascinating world of APIs! An API (Application Programming Interface) is a set of rules that allow two applications to communicate with each other. Think of it as a restaurant menu. When you go to a restaurant, you look at the menu and order your food. The kitchen, or the system, then prepares your order and serves it to you. In this case, the menu is akin to an API. It describes what is possible, and the kitchen uses those instructions to prepare your order.

So, how does this apply to web development? Let's take the example of a weather application that shows weather data from different cities. The app fetches this data from a weather API. The app sends a request to the API, similar to placing an order from a menu, and the API returns the requested data, similar to the kitchen serving the food.

Key Components of RESTful APIs with Express.js

One of the core concepts of REST is the use of HTTP methods on resources. These methods are:

  1. GET: Retrieves data. It doesn't change the state or data on the server; it just retrieves it.
  2. POST: Sends data to be processed to a specified resource. This method can change the state and the data on the server.
  3. PUT: Updates some data on the server.
  4. PATCH: Partially updates some data on the server.
  5. DELETE: Deletes some data from the server.
Express Routes for REST APIs

You already know how to create simple routes in Express. However, building a REST API involves creating routes that correspond to the different HTTP methods. For example:

JavaScript
1app.get('/api/posts', getPosts); 2app.post('/api/posts', createPost); 3app.put('/api/posts/:id', updatePost); 4app.delete('/api/posts/:id', deletePost);

In this code, we define different route handlers (i.e., callback functions) for different types of HTTP requests to /posts.

Each route handler gets three parameters:

  • The request (req): Contains all the information and methods related to the client's request.
  • The response (res): Contains all the information and methods for the server to respond with.
  • Next: A callback that tells Express to go to the next middleware function in the stack.
Implementing a Simple RESTful API

Next, we'll implement a simple RESTful API. One of the great features of Express.js is its ability to easily structure such APIs:

JavaScript
1const express = require('express'); 2const app = express(); 3app.use(express.json()); 4 5let posts = [{id: 1, text: 'Hello, CodeSignal'}]; 6 7// Endpoint for retrieving all existing posts 8app.get('/api/posts', (req, res) => res.json(posts)); 9 10// Endpoint for adding a new post 11app.post('/api/posts', (req, res) => { 12 const newPost = { 13 id: Date.now(), 14 text: req.body.text 15 }; 16 posts.push(newPost); 17 res.json(newPost); 18}); 19 20// Endpoint for updating the existing post 21app.put('/api/posts/:id', (req, res) => { 22 const post = posts.find((post) => post.id === Number(req.params.id)); 23 if (post) { 24 // Update the post if it was found by the provided id 25 post.text = req.body.text; 26 res.json(post); 27 } else { 28 // if the post wasn't found - return status HTTP 404 (Not Found) 29 res.sendStatus(404); 30 } 31}); 32 33// Endpoint for deleting the existing post 34app.delete('/api/posts/:id', (req, res) => { 35 const index = posts.findIndex((post) => post.id === Number(req.params.id)); 36 if (index !== -1) { 37 // Delete the post if it was found by the provided id 38 const deletedPost = posts.splice(index, 1); 39 res.json(deletedPost); 40 } else { 41 // if the post wasn't found - return status HTTP 404 (Not Found) 42 res.sendStatus(404); 43 } 44}); 45 46app.listen(5000, () => console.log('App listening on port 5000'));

To interact with this API, we can use different HTTP methods with the /posts endpoint. We can get all posts, create a new post, update a post, and delete a post.

Accessing RESTful API from a React Client

In previous lessons, you were introduced to Axios for sending HTTP requests from a React client. Now, we'll use it with our new API. Let's create a component that displays a list of posts and includes functions for creating, updating, and deleting posts:

JavaScript
1import { useEffect, useState } from 'react'; 2import axios from 'axios'; 3 4const Posts = () => { 5 const [posts, setPosts] = useState([]); 6 7 useEffect(() => { 8 const fetchPosts = async () => { 9 const res = await axios.get('/api/posts'); 10 setPosts(res.data); 11 }; 12 fetchPosts(); 13 }, []); 14 15 // Other functions to add, update, and delete posts go here 16 17 return ( 18 <div> 19 {posts.map((post) => ( 20 <p key={post.id}>{post.text}</p> 21 ))} 22 </div> 23 ); 24}; 25 26export default Posts;

In this code, we're fetching the posts from /api/posts when the component mounts and updating our state with the fetched posts.

Lesson Summary

We've arrived at the end of our journey with REST APIs! In this lesson, you learned how to create and design RESTful APIs using Express.js and how to interact with these APIs using a React client and Axios. With Express.js and APIs, your server-side web development capabilities have certainly reached a new level! The universe of server-side programming is right at your fingertips, ready to be explored further. Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.