Introduction to API integration in TypeScript using fetch
Integrating external APIs is a cornerstone of building dynamic and feature-rich applications. We need to call external services to enrich the functionality of our application. For the sake of this book, we will need to integrate the OpenAI API to generate Generated Pre-trained Transformer (GPT) responses. Integrating with external APIs is essential but comes with a few things to watch out for: the API call can take a significant time, it can fail, and we can get back something we do not expect as a message with a different structure. We will go through how to mitigate all of the difficulties, and we will start by showing how to communicate with an external API using the native fetch
method.
The fetch
interface allows you to make HTTP requests to servers from our backend. It’s a good choice for API communication for several reasons:
- Native support:
fetch
is natively available in modern browsers, eliminating...