Integration with External APIs

FaasPlus enables your functions to make external REST API calls, allowing you to integrate seamlessly with third-party services, retrieve data, and extend your function’s capabilities. This is achieved by using the injected fetch function, a standard Node.js feature for making HTTP requests.

Using fetch for External Calls

When writing a FaasPlus function, you can inject the fetch function as a parameter, enabling the function to send HTTP requests to remote servers. The fetch function provides flexibility to make GET, POST, PUT, DELETE, or other HTTP requests as needed.

const handleRequest = async (fetch) => {
  // Example of making a GET request
  const response = await fetch('_service_url_address_');
  const data = await response.json();

  return data;
};

In this example, the fetch function is used to make a GET request to an external API. The response is parsed as JSON and returned by the function.

Making Various HTTP Requests

With fetch, you can configure different types of HTTP requests to interact with remote services. Here are examples of common use cases:

  • GET Request: Retrieve data from a service.
    const handleRequest = async (fetch) => {
      const response = await fetch('_service_url_address_');
      return await response.json();
    };
  • POST Request: Send data to an service.
    const handleRequest = async (fetch) => {
      const response = await fetch('_service_url_address_', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ key: 'value' })
      });
      return await response.json();
    };
                

Handling Responses and Errors

When making external calls, it’s important to handle responses and errors gracefully. The fetch function allows you to check response statuses and catch any errors that may occur during the request.

const handleRequest = async (fetch) => {
  try {
    const response = await fetch('_service_url_address_');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return await response.json();
  } catch (error) {
    return { error: error.message };
  }
};

This example checks the response status and returns an error message if the request fails. This helps ensure your function can handle connectivity issues or API errors smoothly.

Summary

Using fetch within FaasPlus functions provides a straightforward way to connect with external APIs and services. By leveraging fetch, you can expand your function’s capabilities, retrieving or sending data to remote servers as part of your application logic.