mennen-online/simple-api-connector

通过配置文件简单配置您要连接的每个API

0.6.0 2023-10-17 09:28 UTC

This package is auto-updated.

Last update: 2024-09-17 11:45:57 UTC


README

描述

厌倦了重复编写相同的API连接器流程吗?

使用此包节省时间

现在您可以通过Laravel的配置文件以简单的方式连接第三方API:

安装

composer require mennen-online/simple-api-connector

用法

在config/api目录中创建一个新的配置文件,例如my-shopware6-shop.php,将以下内容粘贴到文件中:

return [
    'fallback_response_model' => \MennenOnline\SimpleApiConnector\Models\BaseResponseModel::class,
    'base_url' => 'https://example.com/api',
    'authentication' => [
        'type' => 'basic', // basic, bearer, token, digest, client_credentials
        'username' => '', //use for basic and digest
        'password' => '', //use for basic and digest
        'token' => '', //use for bearer and token
        'client_id' => '', //use for client_credentials
        'client_secret' => '', //use for client_credentials
        'authentication_url' => '' //use for client_credentials
    ],
    'endpoints' => [
        'categories' => '/categories',
        'products' => '/products',
        'users/:id' => '/users/:id',
        'users/:user_id/orders/:order_id' => '/users/:user_id/orders/:order_id
    ],
    'response_models' => [
        'categories' => 'Model::class', //Response model for Categories
        'products' => 'Model::class', //Response model for Products
    ]

现在我们将探讨单个数组键及其含义

  • fallback_response_model => 如果为特定端点未定义响应模型,我们将使用此模型
  • base_url => API的基本URL
  • authentication.type => API使用的认证方法
  • authentication.username => 用于基本和摘要认证的用户名
  • authentication.password => 用于基本和摘要认证的密码
  • authentication.token => 用于bearer和token认证的令牌
  • authentication.client_id => 用于客户端凭证认证的客户端ID
  • authentication.client_secret => 用于客户端凭证认证的客户端密钥
  • authentication.authentication_url => 用于客户端凭证认证的认证URL
  • endpoints => API的端点,格式为endpoint_name => endpoint_url
  • response_models => API的响应模型,格式为endpoint_name => response_model

此包允许GET、POST、PUT和DELETE请求。

使用以下代码实例化API连接器:

$connector = new \MennenOnline\SimpleApiConnector\Connector\ApiConnector('my-shopware6-shop');

// To Call the API use the following code:

// GET
$response = $connector->get('categories');

// POST
$response = $connector->post('categories', ['name' => 'My Category']);

// PUT
$response = $connector->put('categories/1', ['name' => 'My Category']);

// DELETE
$response = $connector->delete('categories/1');


// To use URLs with names ID
$response = $connector->get('users/:id', [':id' => 1]);

// To use URLs with multiple names ID
$response = $connector->get('users/:user_id/orders/:order_id', [':user_id' => 1, ':order_id' => 1]);