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

问题描述

我是 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 对象中找到完整的对象,并在其中找到真实的 mediaId。然后搜索 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": []
            }
}