WEB Programming
04-REST API

REST API

  • REST (Representational State Transfer) or RESTful APIs use the HTTP protocol (e.g., GET, POST, PUT, DELETE) and standard message formats (e.g., JSON, XML) to perform CRUD operations (Create, Read, Update, Delete) on a data source.
  • RESTful architecture allows any client that can handle HTTP requests and JSON to access the data, simplifying front-end development and removing specific programming language requirements.

Route Configuration

Define routes to perform CRUD operations on a user collection:

{userId: number, fName: string, lName: string}
RouteHTTP MethodDescription
/api/usersGETGet all the users
/api/usersPOSTCreate a user
/api/users/:userIdGETGet a single user
/api/users/:userIdPUTUpdate a user with new information
/api/users/:userIdDELETEDelete a user

Express Server Code Example:

const express = require('express');
const app = express();
 
const HTTP_PORT = process.env.PORT || 8080;
 
app.get('/api/users', (req, res) => {
  res.send({ message: 'fetch all users' });
});
 
app.post('/api/users', (req, res) => {
  res.send({ message: 'add a user' });
});
 
app.get('/api/users/:userId', (req, res) => {
  res.send({ message: `get user with Id: ${req.params.userId}` });
});
 
app.put('/api/users/:userId', (req, res) => {
  res.send({ message: `update User with Id: ${req.params.userId}` });
});
 
app.delete('/api/users/:userId', (req, res) => {
  res.send({ message: `delete User with Id: ${req.params.userId}` });
});
 
// setup http server to listen on HTTP_PORT
app.listen(HTTP_PORT, () => {
  console.log(`Express http server listening on: ${HTTP_PORT}`);
});

URL + HTTP Method: Acts as a query mechanism for the data source. For example, /api/users/3 or /api/users/twelve will be accepted and processed.


AJAX Testing (View)

  • Setup: Create a views folder and add index.html.
  • Serve HTML: Add route to serve the HTML file using Express:
const path = require('path');
 
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, '/views/index.html'));
});

AJAX Requests in HTML:

<!doctype html>
<html>
  <head>
      <title>API Test</title>
      <script>
          function makeAJAXRequest(method, url, body) {
              fetch(url, {
                  method: method,
                  body: JSON.stringify(body),
                  headers: { 'Content-Type': 'application/json' }
              })
              .then(response => response.json())
              .then(json => {
                  console.log(json);
              });
          }
      </script>
  </head>
  <body>
      <p>Test the API by outputting to the browser console:</p>
      <button type="button" onclick='makeAJAXRequest("GET", "/api/users")'>Get All Users</button><br /><br />
      <button type="button" onclick='makeAJAXRequest("POST", "/api/users", {fName: "Bob", lName: "Jones"})'>Add New User</button><br /><br />
      <button type="button" onclick='makeAJAXRequest("GET", "/api/users/2")'>Get User</button><br /><br />
      <button type="button" onclick='makeAJAXRequest("PUT", "/api/users/2", {fName: "Wanda", lName: "Smith"})'>Update User</button><br /><br />
      <button type="button" onclick='makeAJAXRequest("DELETE", "/api/users/2")'>Delete User</button>
  </body>
</html>

Testing: Run the server and use browser developer tools to check responses and request payloads.


Adding Data (JSON)

  • Middleware: Use express.json() to parse incoming JSON data:
app.use(express.json());
  • Update Routes: Modify routes to handle data using req.body:
app.post('/api/users', (req, res) => {
  res.send({ message: `add the user: ${req.body.fName} ${req.body.lName}` });
});
 
app.put('/api/users/:userId', (req, res) => {
  res.send({ message: `update User with Id: ${req.params.userId} to ${req.body.fName} ${req.body.lName}` });
});

Cross-Origin Resource Sharing (CORS)

Cross-Origin Resource Sharing (CORS) lets web servers decide which other websites can access their resources. It allows web pages to request resources from a different domain than the one that served the web page. This helps to bypass the browser's same-origin policy, which normally blocks such cross-domain requests.

Why CORS is Important

  • Security: Prevents unauthorized access to resources.
  • Privacy: Protects user data from being accessed by unauthorized websites.
  • Flexibility: Allows web pages to access resources from different domains.

Enabling CORS in Express.js

To enable CORS in an Express.js application, you can use the cors middleware. This middleware allows you to configure how your server handles cross-origin requests.

  • Install: Use the cors package to enable CORS in Express:
npm install cors
  • Setup: Add the following code to enable CORS:
const cors = require('cors');
app.use(cors());
  • Configuration: You can configure CORS to allow specific origins, methods, and headers:
app.use(cors({
  origin: 'http://example.com', // Allow only this origin
  methods: ['GET', 'POST', 'PUT', 'DELETE'], // Allow specific methods
  allowedHeaders: ['Content-Type', 'Authorization'] // Allow specific headers
}));
  • Import and Use the Middleware example:
const express = require('express');
const cors = require('cors');
const app = express();
 
app.use(cors());
 
// Define your routes here
 
const HTTP_PORT = process.env.PORT || 8080;
app.listen(HTTP_PORT, () => {
  console.log(`Express http server listening on: ${HTTP_PORT}`);
});

By default, cors() allows all origins. You should configure it according to your security requirements.