DEV Community

tonybui1812
tonybui1812

Posted on

API gateway sample

When you have an Order Service and a Payment Service that both need to list products via an API Gateway, you can structure your code as follows:

1. API Gateway Code:

Your API Gateway code, which could be implemented using a framework like Express.js in Node.js, would handle incoming requests from the Order and Payment Services and route them to the appropriate microservice (Product Service) to fetch the product listings.

const express = require('express');
const request = require('request'); // Or you can use a more advanced HTTP client library

const app = express();
const port = 3000;

// Define routes for listing products
app.get('/order/products', (req, res) => {
  // Forward the request to the Product Service
  const productServiceUrl = 'http://product-service-url/products';

  request(productServiceUrl, (error, response, body) => {
    if (!error && response.statusCode === 200) {
      res.send(body);
    } else {
      res.status(500).send('Error fetching product data');
    }
  });
});

app.get('/payment/products', (req, res) => {
  // Forward the request to the Product Service
  const productServiceUrl = 'http://product-service-url/products';

  request(productServiceUrl, (error, response, body) => {
    if (!error && response.statusCode === 200) {
      res.send(body);
    } else {
      res.status(500).send('Error fetching product data');
    }
  });
});

// Start the API Gateway
app.listen(port, () => {
  console.log(`API Gateway listening at http://localhost:${port}`);
});
Enter fullscreen mode Exit fullscreen mode

2. Order Service Code:

In your Order Service, you would make a request to the API Gateway to retrieve product listings.

const request = require('request'); // Or use a similar HTTP client library

// Define a function to fetch product listings from the API Gateway
function fetchProductListings() {
  return new Promise((resolve, reject) => {
    const apiGatewayUrl = 'http://api-gateway-url/order/products';

    request(apiGatewayUrl, (error, response, body) => {
      if (!error && response.statusCode === 200) {
        resolve(JSON.parse(body));
      } else {
        reject('Error fetching product data from API Gateway');
      }
    });
  });
}

// Usage in your Order Service
fetchProductListings()
  .then((products) => {
    // Process and use the product listings
    console.log(products);
  })
  .catch((error) => {
    // Handle errors appropriately
    console.error(error);
  });
Enter fullscreen mode Exit fullscreen mode

3. Payment Service Code:

Similarly, in your Payment Service, you would also make a request to the API Gateway to retrieve product listings.

const request = require('request'); // Or use a similar HTTP client library

// Define a function to fetch product listings from the API Gateway
function fetchProductListings() {
  return new Promise((resolve, reject) => {
    const apiGatewayUrl = 'http://api-gateway-url/payment/products';

    request(apiGatewayUrl, (error, response, body) => {
      if (!error && response.statusCode === 200) {
        resolve(JSON.parse(body));
      } else {
        reject('Error fetching product data from API Gateway');
      }
    });
  });
}

// Usage in your Payment Service
fetchProductListings()
  .then((products) => {
    // Process and use the product listings
    console.log(products);
  })
  .catch((error) => {
    // Handle errors appropriately
    console.error(error);
  });
Enter fullscreen mode Exit fullscreen mode

In this setup:

  • The API Gateway handles requests from both the Order and Payment Services.
  • Each service makes a request to the appropriate endpoint on the API Gateway to retrieve product listings.
  • The API Gateway forwards the requests to the Product Service and returns the product listings to the requesting service.

This structure allows you to centralize the handling of product listings, making it easier to manage and maintain this functionality across multiple services.

Top comments (1)

Collapse
 
johnodhiambo profile image
JohnOdhiambo

Brief and to the point. Good stuff