我有一个 symfony 项目,在那里我使用 api-platform。
我有一个实体,我有它的数据提供者。我在定义集合端点的附加参数时遇到了麻烦。
实体称为建议。它必须从 Elasticsearch 返回文档集合。
一个端点是:
/suggestion
此端点监听其他 GET 参数:page, level
每次请求端点时都会读取这两个参数。
在我的
SuggestionsCollectionDataProvider.php
我有课:/**
* Retrieves a collection.
*
* @param string $resourceClass
* @param string|null $operationName
* @return \Generator
*/
public function getCollection(string $resourceClass, string $operationName = null): \Generator
{
$query = $this->requestStack->getCurrentRequest()->query;
// I am reading these two parameters from RequestStack
// this one is built-in
$page = max($query->get('page', 1), 1);
// this is a custom one
$level = $query->get('level', 0);
...
在我的 SuggestionRepository.php
类(class):/**
* @return \Generator
*/
public function find(int $page, int $level): \Generator
{
// here I can process with $level without problems
页面参数是默认参数,即为集合生成 Swagger 。API 平台生成的 Swagger 文档截图:
但是页参数现在是 唯一的参数 , 可以在网络版本中编辑。
我需要添加更多参数(在本例中为
level
)以 Swagger 并描述它们,以便用户/测试人员知道哪个参数实际到达此端点。主要问题:
如何告诉 api-platform,我希望 API 的用户/测试人员(来自客户端)输入一些其他参数,即
level
例如?
最佳答案
终于想通了。
我还没有找到它的文档,但我找到了一种方法。
在实体类中 Suggestion.php
我添加了几行 注释 :
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiProperty;
use ApiPlatform\Core\Annotation\ApiResource;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Class Suggestion. Represents an entity for an item from the suggestion result set.
* @package App\Entity
* @ApiResource(
* collectionOperations={
* "get"={
* "method"="GET",
* "swagger_context" = {
* "parameters" = {
* {
* "name" = "level",
* "in" = "query",
* "description" = "Levels available in result",
* "required" = "true",
* "type" : "array",
* "items" : {
* "type" : "integer"
* }
* }
* }
* }
* }
* },
* itemOperations={"get"}
* )
*/
API 平台 swagger DOC 中的结果 View :
关于php - 如何使用 swagger 文档在 api-platform 的端点中请求额外的 GET 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50369988/