1.7 KiB
title, description
| title | description |
|---|---|
| 2. Hook up your data sources | Start here for the Apollo fullstack tutorial |
Apollo data sources provide the best experience for fetching and caching data from REST endpoints, web services, and databases. It's a new pattern for loading data from various sources, with built-in support for deduplication, caching, and error handling.
Connect a REST API
To get started connecting to a REST API, install the apollo-datasource and apollo-datasource-rest packages:
npm install apollo-datasource-rest
The apollo-datasource-rest exposes the RESTDataSource class that is responsible for fetching data from a given REST API. To define a data source for the REST endpoint, extend the RESTDataSource class and implement the data fetching methods that your resolvers require. Let's look at a simple example to understand how data sources work.
import { RESTDataSource } from 'apollo-datasource-rest';
export class MvrpAPI extends RESTDataSource {
constructor() {
super();
this.baseURL = 'https://mvrp.herokuapp.com/api/';
}
async getAllCars() {
return this.get('cars');
}
async getACar(plateNumber) {
const result = await this.get('car', {
plateNumber
});
return result[0];
}
};
The https://mvrp.herokuapp.com/api/ endpoint is a simple REST API that returns data for cars.
The MvrpAPI class implementation in the code above contains a getAllCars and getACar functions that wrap convenience methods provided by the RESTDataSource class for performing HTTP requests. In this example, we used the built-in get method that's responsible for GET requests.