psx/api

解析和生成API规范格式

v7.1.6 2024-09-22 20:37 UTC

README

API组件是TypeAPI规范的参考实现。它提供模型来描述REST API并根据这些模型生成不同的输出。您可以通过解析TypeAPI或OpenAPI规范或使用PHP属性来创建这些模型。基于这些模型,您可以生成例如客户端SDK。

用法

根模型对象被称为Specification,它包含OperationsDefinitions。每个操作映射到特定的REST API端点,定义表示描述JSON请求或响应负载的架构。

框架

您可以使用PHP属性来描述端点的结构。然后,您可以使用属性解析器(PSX\Api\Parser\Attribute)自动生成控制器的规范。一个控制器类可能看起来像这样

<?php

class MyController
{
    #[Get]
    #[Path('/my/endpoint/:id')]
    public function getModel(#[Param] int $id, #[Query] int $year): \My\Response\Model
    {
        // @TODO implement
    }
    
    #[Post]
    #[Path('/my/endpoint')]
    public function insertModel(#[Body] \My\Request\Model $model): \My\Response\Model
    {
        // @TODO implement
    }
}

这足以让API组件生成OpenAPI规范或客户端SDK。请注意,此库只需要元信息,如果您可以在框架中以另一种方式获取这些元信息,您也可以实现自定义的ParserInterface

独立

除了框架集成之外,您还可以使用此组件简单地解析现有的TypeAPI规范并生成特定输出。以下是一个如何使用PHP API以及如何生成代码的简单示例。

<?php

// use the API manager to obtain a specification from different sources
$manager = new \PSX\Api\ApiManager(new \PSX\Schema\SchemaManager());

// reads the TypeAPI specification and generates a specification
$specification = $manager->getApi('./typeapi.json');

// contains all schema type definitions
$definitions = $specification->getDefinitions();

// returns the resource foo from the specification
$operation = $specification->getOperations()->get('my.operation');

// returns all available arguments
$operation->getArguments();

// returns the return type
$operation->getReturn();

// returns all exceptions which are described
$operation->getThrows();

// returns the assigned HTTP method
$operation->getMethod();

// returns the assigned HTTP path
$operation->getPath();

// creates a PHP client which consumes the defined operations
$registry = \PSX\Api\GeneratorFactory::fromLocal()->factory();
$generator = $registry->getGenerator(\PSX\Api\Repository\LocalRepository::CLIENT_PHP)

$source = $generator->generate($resource);

生成器

客户端

  • PHP
  • Typescript

标记

  • 客户端
  • HTML
  • Markdown

规范