如何使用 Rest API 获取 Shopware 6 中产品的媒体文件?

How can I fetch the media files of the products in Shopware 6 using Rest API?

我是 Shopware 的初学者,大部分时间都在关注文档。根据 REST API https://docs.shopware.com/en/shopware-platform-dev-en/how-to/working-with-the-api-and-an-http-client

的文档

我可以通过调用 request 函数来检索产品数据

$this->restService->request('GET', 'product');

基本上,它发出以下请求,返回我的产品数据。

private function createShopwareApiRequest(string $method, string $uri, ?string $body = null): RequestInterface
{
    return new Request(
        $method,
        getenv('APP_URL') . '/api/v3/' . $uri,
        [
            'Authorization' => 'Bearer ' . $this->accessToken,
            'Accept' => '*/*'
        ],
        $body
    );
}

我找不到与产品相关的媒体文件。谁能帮助我如何获取产品和图片?

您需要在请求中添加 association 参数。对于 GET 产品请求,它应该如下所示 /api/v3/product?associations[media][]

当您在产品响应中执行此操作时,您将获得如下对象:

"media": {
            "data": [
                {
                    "type": "product_media",
                    "id": "41e9b70e1df84b999bbf08ce7bf3fb77"
                }
            ],
            "links": {
                "related": "http://localhost:8000/api/v3/product/a1d20f10d019491fbf889ad5651aab23/media"
            }
        },

通过产品媒体ID,您可以在included您的响应对象中找到完整的对象,并在其中找到真实的媒体ID。然后搜索 mediaId 包含的媒体对象。

{
        "id": "41e9b70e1df84b999bbf08ce7bf3fb77",
        "type": "product_media",
        "attributes": {
            "versionId": "0fa91ce3e96a4bc2be4bd9ce752c3425",
            "productId": "a1d20f10d019491fbf889ad5651aab23",
            "productVersionId": "0fa91ce3e96a4bc2be4bd9ce752c3425",
            "mediaId": "1bf12b4bae5e4d288ce049aacfd2cc24",
            "position": 1,
            "customFields": null,
            "createdAt": "2020-05-22T13:10:37.255+00:00",
            "updatedAt": null,
            "apiAlias": null
        }
},
{
        "id": "1bf12b4bae5e4d288ce049aacfd2cc24",
        "type": "media",
        "attributes": {
            "userId": null,
            "mediaFolderId": "fd22d1ef41994f6ea05f9b4cb01d85d3",
            "mimeType": "image/jpeg",
            "fileExtension": "jpg",
            "uploadedAt": "2020-05-22T13:10:37.227+00:00",
            "fileName": "10062415_1",
            "fileSize": 74503,
            "metaData": {
                "type": 2,
                "width": 1500,
                "height": 1000
            },
            "mediaType": {
                "name": "IMAGE",
                "flags": [],
                "extensions": []
            }
}