API Services

Component ID

2620774

Component name

API Services

Component type

module

Maintenance status

Development status

Component security advisory coverage

covered

Downloads

432

Component created

Component changed

Component body

About API Services

The API services module provides a framework for managing third-party API endpoints using configurable entities.

Developers can then create requests to these endpoints using an API provider implementation, and send the requests using an API client service.

Features

Endpoints are configuration entities:

Since each endpoint is a configuration entity, they can be managed using Drupal's configuration API. This allows each endpoint to be accessible to other modules, enabled or disabled individually, and have dependencies that are automatically managed by Drupal.

Custom API providers:

Every third-party API has unique features. API providers are how requests are customized accordingly. For example, providers can support setting placeholders in an endpoint's path. They also allow for simple GET requests and more complex methods, such as POST or PATCH requests, to be implemented.

Send requests and manage responses using a client service:

Implementing a client service allows you to control how a request is sent and what happens to all those server responses. For example, the default implementation provided by this module sends requests using the HTTP client included with Drupal and caches responses using a specified backend, but a custom client could add authentication data (such as for OAuth 2.0) or delegate the request to AWS/Azure.

Developer Guide

Making requests:

// An actual provider would probably also let you set custom variables...
$provider = new ExampleApiProvider('example.news');
$response = Drupal::service('example.client')->request($provider);

Implementing a new API:

  1. Implement an API provider.
    class ExampleApiProvider extends ApiProviderBase {
      public function getRequestUrl() {
        return 'http://example.com' . $this->endpoint->getPath();
      }
    }
  2. Add endpoint entities.
    # File: apiservices.endpoint.example.news.yml
    id: example.news
    name: 'Example: News'
    path: '/news'
    provider: '/Drupal/example/ExampleApiProvider'
  3. Create an API client service.
    # File: example.services.yml
    services:
      example.client:
        parent: apiservices.client_base
        arguments: ['@http_client', '@cache.example', '@logger.channel.example']
      # Add cache and logger service definitions here.