要从特定操作中获取数据,您可以使用Api-Platform和GraphQL进行以下步骤:
type Query {
getBooks: [Book!]!
getBook(id: ID!): Book
}
@ApiResource
注解来定义GraphQL的查询操作。在资源类中,您可以使用@Query
注解来定义特定的操作。例如,以下是一个使用@Query
注解获取书籍的操作:use ApiPlatform\Core\Annotation\ApiResource;
use ApiPlatform\Core\Annotation\ApiProperty;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* @ApiResource(
* graphql={
* "item_query"={
* "method"="GET",
* "path"="/books/{id}"
* },
* "collection_query"={
* "method"="GET",
* "path"="/books"
* }
* }
* )
*/
class Book
{
/**
* @ApiProperty(identifier=true)
* @Groups({"read"})
*/
public $id;
/**
* @Groups({"read"})
*/
public $title;
}
query {
getBook(id: 1) {
id
title
}
}
use Symfony\Contracts\HttpClient\HttpClientInterface;
class BookApiClient
{
private $httpClient;
public function __construct(HttpClientInterface $httpClient)
{
$this->httpClient = $httpClient;
}
public function getBook(int $id): array
{
$response = $this->httpClient->request('POST', '/api/graphql', [
'json' => [
'query' => '
query {
getBook(id: ' . $id . ') {
id
title
}
}',
],
]);
return $response->toArray();
}
}
这样,您就可以从特定操作中使用Api-Platform和GraphQL获取数据了。请注意,这只是一个简单的示例,您可以根据自己的需求进行更复杂的查询和操作。