标签: api-platform.com

使用swagger文档在api平台的端点中询问其他GET参数

我有一个symfony项目,在这里我使用api平台。我有一个实体,也有它的数据提供者。我在定义集合终结点的其他参数时遇到麻烦。

实体称为建议。它必须从弹性搜索返回文档集合。

端点是:

/suggestion
Run Code Online (Sandbox Code Playgroud)

该端点侦听其他GET参数:

页面,级别

每次在请求端点时都会读取这两个参数。

在我的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); 
        ...
Run Code Online (Sandbox Code Playgroud)

在我的SuggestionRepository.php课上:

/**
     * @return \Generator
     */
    public …
Run Code Online (Sandbox Code Playgroud)

yaml annotations symfony swagger api-platform.com

6
推荐指数
2
解决办法
2406
查看次数

如何通过自定义操作使用默认 API 平台过滤器?

我有自定义操作(在文档中看到为推荐方法),可以生成一些逻辑并返回实体的学说集合。

\n\n

常规 api 平台操作过滤器可以完美工作。但是我如何从默认过滤器中获取任何内容以在我的自定义操作中使用此集合?

\n\n

当我请求GET /cars?createdAt[after]=2018-08-01GET /drivers?createdAt[after]=2018-08-01它按预期工作时。

\n\n

但是当我尝试GET /drivers/42/cars_custom_logic?createdAt[after]=2018-08-01这样做时,它不会过滤任何内容。这是预期的,因为我没有在自定义操作中调用过滤器,但我的问题是\xe2\x80\x93 如何添加此过滤器?

\n\n
\n\n

App\\Entity\\Car

\n\n
<?php\n\nnamespace App\\Entity;\n\nuse ApiPlatform\\Core\\Annotation\\ApiFilter;\nuse ApiPlatform\\Core\\Bridge\\Doctrine\\Orm\\Filter\\DateFilter;\nuse Doctrine\\ORM\\Mapping as ORM;\nuse Symfony\\Component\\Serializer\\Annotation\\Groups;\n\n/**\n * @ORM\\Entity\n * @ApiResource\n * @ApiFilter(DateFilter::class, properties={"createdAt"})\n */\nclass Car\n{\n    /**\n     * @ORM\\Id()\n     * @ORM\\GeneratedValue()\n     * @ORM\\Column(type="integer")\n     * @Groups({"car", "driver"})\n     */\n    private $id;\n\n    /**\n     * @ORM\\Column(type="datetime")\n     * @Groups({"car", "driver"})\n     */\n    private $createdAt;\n\n    /**\n     * @ORM\\ManyToOne(targetEntity="App\\Entity\\Driver", inversedBy="cars")\n     * @Groups({"car", "driver"})\n     */\n    private $driver;\n\n    public function …
Run Code Online (Sandbox Code Playgroud)

php symfony api-platform.com

6
推荐指数
1
解决办法
8410
查看次数

如何在 Symfony4 api-platform 中隐藏实体属性

我有这个实体

/**
* @ApiResource(
*       collectionOperations={
*           "get"={
*               "access_control"="is_granted('IS_AUTHENTICATED_FULLY')"
*           },
*           "post"={
*               "access_control"="is_granted('IS_AUTHENTICATED_FULLY')"
*           }
*       },
*       itemOperations={
*       "get"={
*               "access_control"="is_granted('ROLE_ADMIN') or object.getUser() == user"
*           },
*           "put"={
*               "access_control"="is_granted('ROLE_ADMIN') or object.getUser() == user"
*          },
*           "delete"={
*               "access_control"="is_granted('ROLE_ADMIN') or object.getUser() == user"
*          }
*       }
* )
* @ORM\Entity(repositoryClass="App\Repository\FeedRepository")
*/
class Feed implements AuthoredEntityInterface
{
/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="feeds")
 * @ORM\JoinColumn(nullable=false) …
Run Code Online (Sandbox Code Playgroud)

php api symfony api-platform.com

6
推荐指数
1
解决办法
9700
查看次数

如何在 API 平台上保存与实体的嵌套关系

我有两个实体,QuestionAlternative,其中 Question 与 Alternative 有 OneToMany 关系,我正在尝试通过 POST to Question API Platform发送带有Alternative嵌套文档的 JSON 。

API 平台在下面返回该错误:

Nested documents for "alternatives" attribute are not allowed. Use IRIs instead.
Run Code Online (Sandbox Code Playgroud)

搜索它我发现有些人说这只能使用 IRI,而其他一些人说可以使用非规范化和规范化上下文来解决这个问题,但我找不到关于它的一些示例或教程。

TL; 博士;

有没有办法在不使用 IRI 的情况下将嵌套关系发送到 API 平台上的实体 POST 中?

更新:

如所问,请参阅下面的问题和替代实体的两个映射。

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use DateTimeInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\QuestionRepository")
 * @ApiResource()
 */
class Question implements CreatedAtEntityInterface, UpdatedAtEntityInterface
{
    /**
     * …
Run Code Online (Sandbox Code Playgroud)

php symfony api-platform.com

6
推荐指数
2
解决办法
8803
查看次数

如何使用 PHP 从 ApiPlatform 反序列化 JSON-LD

我已经使用 ApiPlatform 成功为我的系统构建了一个 API。感谢开发人员,这是一个出色的系统。我可以以 JSON-LD 格式向它发送请求,它也以 JSON-LD 格式返回响应。

我了解使用 JSON-LD 的好处,但我觉得我错过了一大块拼图。如何在我基于 Symfony 的 PHP 客户端(使用 API)中使用嵌入式 JSON-LD 上下文反序列化为 PHP 对象。

假设我的 API 有以下响应

{
  "@context": "/contexts/CallbackRequest",
  "@id": "/callback-requests/72",
  "@type": "CallbackRequest",
  "id": 72,
  "created": "2017-09-22T08:07:25+02:00",
  "customer": {
    "@id": "/customers/13",
    "@type": "Customer",
    "id": 13,
    "firstName": "Joe",
    "lastName": "Bloggs",
    "email": "joe@bloggs.com",
    "mobilePhone": "123456789"
  }
}
Run Code Online (Sandbox Code Playgroud)

现在,由于 JSON-LD @context 和 @type 数据,这里有足够的信息可以反序列化为CallbackRequest具有嵌套对象的2 个 PHP 对象。Customer

我已经编写了自己的反规范化器,但我必须告诉序列化器我想首先反序列化为哪种对象,但如果不首先对其进行规范化,我无法从 JSON-LD 中提取它。

我进行了很多搜索,寻找为 Symfony 序列化器制作 JSON-LD 规范化器/反规范化器的人,但什么也没找到(除了 API 平台包本身内的此功能)。

任何人都可以向我提供任何指针,无论是我可以实现的 JSON-LD 非规范化程序包,还是有关如何实现 Symfony 序列化程序以对 JSON-LD …

serialization symfony api-platform.com

5
推荐指数
0
解决办法
1988
查看次数

自定义过滤器 API 平台不起作用

我正在尝试在 API 平台中实现自定义或过滤器。但由于某种原因,它没有加载。在我的配置下面找到。

这是我的过滤器:

<?php

namespace AppBundle\Filter;

use ApiPlatform\Core\Bridge\Doctrine\Orm\Filter\AbstractFilter;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
use Doctrine\ORM\QueryBuilder;

use Doctrine\Common\Annotations\AnnotationReader;

final class SearchFilter extends AbstractFilter
{
    protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
    {
    if ($property === 'search') {
        $this->logger->info('Search for: ' . $value);
    } else {
        return;
    }

    $reader = new AnnotationReader();
    $annotation = $reader->getClassAnnotation(new \ReflectionClass(new $resourceClass), \AppBundle\Filter\SearchAnnotation::class);

    if (!$annotation) {
        throw new \HttpInvalidParamException('No Search implemented.');
    }

    $parameterName = $queryNameGenerator->generateParameterName($property);
    $search = [];
    $mappedJoins = []; …
Run Code Online (Sandbox Code Playgroud)

api-platform.com

5
推荐指数
1
解决办法
7383
查看次数

Symfony 和 API 平台 - 通过 slug 或 userToken 或任何其他不同于 ID 的字段检索数据

我想做的是:

  • 从我的前端向 API 自定义 url 发送请求以激活用户帐户 (/account/activate/someTokenValue)
  • 通过confirmationToken值检索用户表单数据库
  • 激活用户帐户并将其保存到数据库
  • 返回激活信息(或一些错误,例如令牌无效)

所以我定义了:

* @ApiResource(itemOperations={
 *     "get",
 *     "activate_account"={
 *         "method"="get",
 *         "path"="/account/activate/{confirmationToken}",
 *         "controller"=UserActivate::class
 *     }
 * })
 */
Run Code Online (Sandbox Code Playgroud)

在我的User实体类中有一个UserActivate控制器,并由控制器UserActivateHandler调用UserActivate。我已将ApiProperty identifierID设置false为 to 和confirmationTokento true

   /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @ApiProperty(identifier=false)
     *
     */
    private $id;

    /**
      * 
      * @ORM\Column(type="string", nullable=true)
      * @ApiProperty(identifier=true)
      */
    protected $confirmationToken;
Run Code Online (Sandbox Code Playgroud)

但是API Platform仍然需要ID并且它似乎没有看到confirmationToken参数。

基本上我的问题是,在这种情况下,我如何检索对象confirmationToken

php api doctrine symfony api-platform.com

5
推荐指数
1
解决办法
3053
查看次数

API平台按空值过滤

我正在寻找一种解决方案来根据为空的参数(用户)恢复 get 中的数据:

    {
  "@context": "\/api\/contexts\/ShippingCost",
  "@id": "\/api\/shipping_costs",
  "@type": "hydra:Collection",
  "hydra:member": [
    {
      "@id": "\/api\/shipping_costs\/1",
      "@type": "ShippingCost",
      "id": 1,
      "minWeight": 0,
      "maxWeight": 251,
      "france": 4.87,
      "domTom": 4.21,
      "aerial": 3.84,
      "zone": {
        "@id": "\/api\/zones\/1",
        "@type": "Zone",
        "id": 1,
        "name": "Guadeloupe",
        "TaxFOB": 35,
        "TaxSurete": 0.2,
        "TaxFuel": 0.77,
        "TaxGuerre": 0.24,
        "Lta": 0,
        "InfoDouane": 24,
        "CreditEnlevement": 0,
        "EntreposageCci": 0.4,
        "EntreposageCciMin": 15,
        "RemiseDoc": 43,
        "Surete": 0,
        "AvanceFond": 0,
        "Tid": 13,
        "Spia": 10,
        "InterTransite": 50
      },
      "user": null
    },
{
      "@id": "\/api\/shipping_costs\/162",
      "@type": "ShippingCost",
      "id": 162, …
Run Code Online (Sandbox Code Playgroud)

api symfony api-platform.com

5
推荐指数
1
解决办法
4281
查看次数

如何在 Api 平台上使用带有 Messenger 输入的路径中的 {id}?

我有这样的事情:

/**
 * @ORM/Entity
 * @ApiResource(
 *     itemOperations={
 *         "put_cancel": {
 *             "method": "PUT",
 *             "path": "/task/{id}/cancel",
 *             "messenger": "input",
 *             "input": CancelTaskCommand::class,
 *             "output": false
 *         },
 *     }
 * )
 */
class Foo {}
Run Code Online (Sandbox Code Playgroud)

取消FooCommand.php

final class CancelFooCommand
{
    /**
     * @var string
     * @ApiProperty(
     *     identifier=true,
     * )
     */
    public string $id = '';

    /**
     * @var string
     * @ApiProperty(
     *     attributes={
     *         "openapi_context"={
     *           "type": "string"
     *         }
     *     }
     * )
     */
    public string $note …
Run Code Online (Sandbox Code Playgroud)

php symfony api-platform.com

5
推荐指数
0
解决办法
265
查看次数

如何使用 API Platform GraphQL 为必填字段指定默认值?

我希望我的实体上的必填布尔字段具有默认值TRUE。我已将我的#api-platform属性定义如下。

#[ApiResource(
    attributes: ['security' => "is_granted('ROLE_USER')"],
    graphql: [
        'item_query' => ['security' => "is_granted('ROLE_USER') and object.owner == user"],
        'collection_query' => ['security' => "is_granted('ROLE_ADMIN')"],
        'delete' => ['security' => "is_granted('ROLE_DEVELOPER')"],
        'update' => ['security' => "is_granted('ROLE_DEVELOPER')"],
        'create' => [
            'defaults' => ['active' => TRUE],
            'security' => "is_granted('ROLE_DEVELOPER')"
        ]
    ]
)]
Run Code Online (Sandbox Code Playgroud)

活动字段本身注释为

    /**
     * @ORM\Column(type="boolean", options={"default":true})
     */
    private $active;
Run Code Online (Sandbox Code Playgroud)

这确实在数据库模式中设置了默认值,但是 GraphQL 突变似乎仍然要求在请求中提供此属性。当尝试创建一个不指定activeprop 的新实体时,我收到以下错误。

... Field value.active of required type Boolean! was not provided.
Run Code Online (Sandbox Code Playgroud)

graphql api-platform.com

5
推荐指数
1
解决办法
1106
查看次数