chaplean/rest-client-bundle

快速创建 Restful API 客户端

安装数: 7,940

依赖者: 3

建议者: 0

安全性: 0

星标: 0

关注者: 1

分支: 0

开放性问题: 0

类型:symfony-bundle

v4.0.1 2018-12-06 09:43 UTC

This package is auto-updated.

Last update: 2024-08-28 12:41:17 UTC


README

Codeship Status for chaplean/rest-client-bundle Coverage Status

先决条件

此版本的包需要 Symfony 2.8+。

安装

1. Composer

composer require chaplean/rest-client-bundle

2. AppKernel.php

添加

new EightPoints\Bundle\GuzzleBundle\EightPointsGuzzleBundle(),
new Chaplean\Bundle\RestClientBundle\ChapleanRestClientBundle(),

// If you want to enable Database logging
new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),

// If you want to enable Email logging
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\TwigBundle\TwigBundle()

3. config.yml 和 parameters.yml

首先,您需要配置底层的 guzzlehttp,我们用它来执行实际的 HTTP 请求。请参阅 文档或 文档以获取完整选项范围。示例

config.yml

eight_points_guzzle:
    logging: true
    clients:
        fake_api:
            # We inject guzzle configuration from parameters.yml but we could hardcode it here
            options: %fake_api.options%

您可能还需要创建一些自定义参数。

parameters.yml

parameters:
    # Guzzle configuration
    fake_api.options:
        timeout: 10
        verify: false
        expect: false
        
    # Your custom configuration, here we just define the base url of our fake_api
    fake_api.url: 'http://fakeapi.com/'

在您将 guzzle 注入到您的 Api 类中时,您可以针对每个 Api 使用不同的配置。请参阅下一节。

此捆绑包还公开了一些配置,如果您想启用额外功能。您可以启用请求的数据库和/或电子邮件记录。要使用数据库或电子邮件记录器,您必须分别在项目中设置 doctrineswiftmailer。默认配置是

config.yml

chaplean_rest_client:
    enable_database_logging: false
    enable_email_logging: false
    email_logging:
        # Limit emails to the specified codes.
        # You can either use a code directly like 200, 404, …
        # or use XX to say all codes in the familly like 5XX to say all server errors.
        # 0 means that the request failed to run (either because of invalid parameters or a networking error)
        codes_listened: ['0', '1XX', '2XX', '3XX', '4XX', '5XX']
        address_from: ~
        address_to:   ~

您可以通过覆盖翻译键或电子邮件体模板(例如,Resources/views/Email/request_executed_notification.txt.twig)来覆盖默认电子邮件内容。翻译键位于 chaplean_rest_client.email.request_executed_notification

使用方法

创建 Api 类

要使用 rest-client-bundle,您必须创建一个继承自 AbstractApi 的类。您可以创建任意数量的继承自 AbstractApi 的类,并通过依赖注入让它们使用不同的配置。

<?php

use Chaplean\Bundle\RestClientBundle\Api\AbstractApi;
use Chaplean\Bundle\RestClientBundle\Api\Parameter;
use GuzzleHttp\ClientInterface;

class FakeApi extends AbstractApi
{
    protected $url;

    /**
     * AbstractApi required you to pass it a GuzzleHttp\ClientInterface, we also inject the base api of our fake_api
     */
    public function __construct(ClientInterface $client, $url)
    {
        parent::__construct($client);

        $this->url = $url;
    }

    /**
     * We define our api here, we'll dig into this in the next section
     */
    public function buildApi()
    {
        $this->globalParameters()
            ->urlPrefix($this->url) // here we set base url
            ->expectsJson();

        $this->get('fake_get', 'fake')
            ->urlParameters([
                'id' => Parameter::id(),
            ]);
    }
}
services:
    app_rest.api.fake:
        class: App\Bundle\RestBundle\Api\FakeApi
        arguments:
            - '@guzzle.client.fake_api' # Guzzle client we defined in config.yml
            - '%fake_api.url%'          # the base url of fake_api

完成!我们可以重复此过程以创建另一个具有完全不同配置的 Api。

定义 Api

让我们专注于您必须填充的 buildApi() 函数以及我们可以在其中做什么。此函数的作用是使用 rest-client-bundle api 定义您的 Api。

<?php

public function buildApi()
{
    /*
     * You have to call this function first to set basic config
     */
    $this->globalParameters()
        ->urlPrefix('http://some.url/')  // set the base url of our api

    /*
     * We can then set some configurations that will be the default for every route we create later.
     * You have the exact same api available here and available when configuring routes.
     * See route definition for detailed descriptions of headers(), urlParameters(), queryParameters() and requestParameters()
     */
        ->expectsPlain()                 // Declare we expect responses to be plain text
        ->expectsJson()                  // Declare we expect responses to be json
        ->expectsXml()                   // Declare we expect responses to be xml

        ->sendFormUrlEncoded()           // Configure that we post our data as classic form url encoded  (only apply to post, put and patch requests)
        ->sendJson()                     // Configure that we post our data as json (only apply to post, put and patch requests)
        ->sendXml()                      // Configure that we post our data as xml (only apply to post, put and patch requests)
        ->sendJSONString()               // Configure that we post our data as a url-encoded key-value pair where the key is JSONString and the value is the request data in json format (only apply to post, put and patch requests)

        ->headers([])                    // Configure what headers we send
        ->urlParameters([])              // Configure what url placeholders we define
        ->queryParameters([])            // Configure what query strings we send
        ->requestParameters([]);         // Configure what post data we send (only apply to post, put and patch requests)

    /*
     * Here we define the core of our api, the routes. We can use get(), post(), put(), patch(), delete() functions
     * with a route name and a route url (with placeholders in you want) to define routes.
     */
    $this->get('query_one', 'data/{id}');
    $this->post('create_one', 'data');
    $this->patch('update_one', 'data/{id}');
    $this->put('update_one', 'data/{id}');
    $this->delete('delete_one', 'data/{id}');

    /*
     * Those function return the route object to further configure it.
     * As said previously the route api is the same as the one we get with globalParameters().
     */
    $this->post('create_one', 'data/{id}')
        ->expectsPlain()                 // Declare we expect responses to be plain text
        ->expectsJson()                  // Declare we expect responses to be json
        ->expectsXml()                   // Declare we expect responses to be xml

        ->sendFormUrlEncoded()           // Configure that we post our data as classic form url encoded  (only apply to post, put and patch requests)
        ->sendJson()                     // Configure that we post our data as json (only apply to post, put and patch requests)
        ->sendXml()                      // Configure that we post our data as xml (only apply to post, put and patch requests)
        ->sendJSONString()               // Configure that we post our data as a url-encoded key-value pair where the key is JSONString and the value is the request data in json format (only apply to post, put and patch requests)

        ->headers([])                    // Configure what headers we send
        ->urlParameters([])              // Configure what url placeholders we define
        ->queryParameters([])            // Configure what query strings we send
        ->requestParameters([]);         // Configure what post data we send (only apply to post, put and patch requests)

    /*
     * Finally calling headers(), urlParameters(), queryParameters() or requestParameters() without configuring parameters is sort of useless.
     * So let's see how to define parameters.
     */
    $this->put('update_data', 'data/{id}')
        ->urlParameters(                 // Define the placeholder parameter for the {id} in the url
            [
                'id' => Parameter::id(),
            ]
        )
    /**
     * We define a list of key => values pairs where key is the name of the parameter and the value is a parameter type.
     * We can also configure the parameters type. They all support at least optional(), defaultValue().
     */
        ->requestParameters(
            [
                'name'     => Parameter::string(),
                'birthday' => Parameter::dateTime('Y-m-d'),
                'is_human' => Parameter::bool()->defaultValue(true),
                'height'   => Parameter::int(),
                'weight'   => Parameter::float()->optional(),
                'tags'     => Parameter::object(
                    [
                        'id'   => Parameter::id(),
                        'name' => Parameter::string(),
                    ]
                ),
                'friends'  => Parameter::arrayList(Parameter::id()),
            ]
        );
}