Accessing Image URL from API data - is this possible?

System Information
  • Strapi Version: 3.5.2
  • Operating System: macOS Catalina 10.15.6
  • Database: sqLite (quickstart)
  • Node Version: 14.15.1
  • NPM Version: 6.14.9
  • Yarn Version: 1.22.1

Hello,

I’m building a simple portfolio website for a photographer. The collection type that I’m trying to display is called pet pictures, with fields for a title and an image. I’m able to call the API with an async function, but once I have the JSON data from the API, I’m not able to access the URL for the photos. I can create a heading that shows the title of each Pet Picture, for example, but I cannot use standard object notation to access the URL in the JSON data and then display the image. Is this literally impossible? I’m losing my mind a bit.

For example, taking an array of JSON data that looks like this:

{
    "id": 1,
    "Title": "Santa Dog Picture",
    "published_at": "2021-03-29T02:45:32.389Z",
    "created_at": "2021-03-29T02:45:23.362Z",
    "updated_at": "2021-03-29T02:45:32.414Z",
    "Photo": {
        "id": 3,
        "name": "Pets3.jpg",
        "alternativeText": "",
        "caption": "",
        "width": 4000,
        "height": 6000,
        "formats": {
            "thumbnail": {
                "name": "thumbnail_Pets3.jpg",
                "hash": "thumbnail_Pets3_a4be530d90",
                "ext": ".jpg",
                "mime": "image/jpeg",
                "width": 104,
                "height": 156,
                "size": 5.74,
                "path": null,
                "url": "/uploads/thumbnail_Pets3_a4be530d90.jpg"
            },
            "large": {
                "name": "large_Pets3.jpg",
                "hash": "large_Pets3_a4be530d90",
                "ext": ".jpg",
                "mime": "image/jpeg",
                "width": 667,
                "height": 1000,
                "size": 85.36,
                "path": null,
                "url": "/uploads/large_Pets3_a4be530d90.jpg"
            },
            "medium": {
                "name": "medium_Pets3.jpg",
                "hash": "medium_Pets3_a4be530d90",
                "ext": ".jpg",
                "mime": "image/jpeg",
                "width": 500,
                "height": 750,
                "size": 56.22,
                "path": null,
                "url": "/uploads/medium_Pets3_a4be530d90.jpg"
            },
            "small": {
                "name": "small_Pets3.jpg",
                "hash": "small_Pets3_a4be530d90",
                "ext": ".jpg",
                "mime": "image/jpeg",
                "width": 333,
                "height": 500,
                "size": 31.39,
                "path": null,
                "url": "/uploads/small_Pets3_a4be530d90.jpg"
            }
        },
        "hash": "Pets3_a4be530d90",
        "ext": ".jpg",
        "mime": "image/jpeg",
        "size": 2031.2,
        "url": "/uploads/Pets3_a4be530d90.jpg",
        "previewUrl": null,
        "provider": "local",
        "provider_metadata": null,
        "created_at": "2021-03-29T02:42:56.325Z",
        "updated_at": "2021-03-29T02:42:56.464Z"
    }
}

This does not work:

const displayPhoto = async () => {
    const response = await fetch('/pet-pictures')
    const petPictures = await response.json()

console.log(petPictures)
const container = document.querySelector('#pets')


petPictures.forEach((picture) =>{
   
const photo = document.createElement('img')
photo.setAttribute('src', picture.Photo.formats.small.url)
container.appendChild(photo)

})

}

displayPhoto()

I get a TypeError: cannot read property ‘formats’ of undefined. But if I replace photo with title, and create an h1 and set it’s text content to picture.title, that works. I’m losing my mind here! Apologies if I’m missing something super obvious and embarrassing.

I hope it’s not too late but for the src to read the image link you need to preceed picture.Photo.formats.small.url with a domain. If you are developing locally you’d put http://localhost:[PORT].

Hello,

The same thing happens to me, but I try to access the images of the products for the e-commerce that I am building with Strapi and Tailwind in NextJS, but I cannot access the images of the products, the chord is as follows:

import React, { useContext } from 'react';
import axios from 'axios';
import AppContext from 'context/AppContext';

function products({ products, error }) {
  const { addToCart } = useContext(AppContext);

  const handleCLick = item => {
		addToCart(item);
	}
  if(error) {
    return <div>An error occured: {error.message}</div>;
  }

  return (
    <div className="bg-white">
      <div className="max-w-2xl lg:pt-6 mx-auto px-4 sm:px-6 lg:max-w-7xl lg:px-8">
        <h2 className="text-tittle font-Roboto tracking-tight text-gray-900">Product Lists</h2>

        <div className="mt-6 grid grid-cols-1 gap-y-10 gap-x-6 sm:grid-cols-2 lg:grid-cols-4 xl:gap-x-8">
          {products.data.map(product => (
            <div key={product.id} className="group relative">
              <div className="w-full min-h-80 bg-gray-200 aspect-w-1 aspect-h-1 rounded-md overflow-hidden group-hover:opacity-75 lg:h-80 lg:aspect-none">
                <img src={`${process.env.imagenURL}/eleven_463d3b72f9.jpg`} alt={product.attributes.tittle} className="w-full h-full object-center object-cover lg:w-full lg:h-full" />
              </div>
              <div className="mt-4 flex justify-between">
                <div>
                  <h3 className="text-sm text-gray-700">
                    <a href={product.href}>
                      <span aria-hidden="true" className="" />
                      {product.attributes.tittle}
                    </a>
                  </h3>
                  <p className="mt-1 text-sm text-gray-500">{product.attributes.description}</p>
                </div>
                <p className="text-sm font-medium text-gray-900">${product.attributes.price}</p>
              </div>
              <div>
                <button onClick={() => handleCLick(product)} className="origin-center hover:translate-y-0.5 delay-btn duration-150 mt-3 w-full h-10 border-4 border-black bg-pink-300 hover:bg-pink-400 shadow-btn1 font-Roboto text-base">
                  Add to cart
                </button>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

products.getInitialProps = async() => {
  try {
    const resOne = await axios.get(`${process.env.apiPublicUrl}/products`);
    console.log(resOne);

    const products = resOne.data;
    return { products };

  } catch (error) {
    return { error };
  }
};

export default products;

I appreciate your help, regards

edit… add postman : http://localhost:1338/api/products?populate=img

{
    "data": [
        {
            "id": 1,
            "attributes": {
                "createdAt": "2022-07-21T16:02:16.965Z",
                "updatedAt": "2022-08-11T01:02:26.417Z",
                "publishedAt": "2022-07-21T16:03:45.251Z",
                "tittle": "eleven",
                "description": "\"Stranger Things\" ",
                "price": 90,
                "qty": 1,
                "creationDate": "2022-07-25",
                "img": {
                    "data": [
                        {
                            "id": 16,
                            "attributes": {
                                "name": "eleven.jpg",
                                "alternativeText": "eleven.jpg",
                                "caption": "eleven.jpg",
                                "width": 1000,
                                "height": 1000,
                                "formats": {
                                    "thumbnail": {
                                        "name": "thumbnail_eleven.jpg",
                                        "hash": "thumbnail_eleven_463d3b72f9",
                                        "ext": ".jpg",
                                        "mime": "image/jpeg",
                                        "path": null,
                                        "width": 156,
                                        "height": 156,
                                        "size": 6.52,
                                        "url": "/uploads/thumbnail_eleven_463d3b72f9.jpg"
                                    },
                                    "medium": {
                                        "name": "medium_eleven.jpg",
                                        "hash": "medium_eleven_463d3b72f9",
                                        "ext": ".jpg",
                                        "mime": "image/jpeg",
                                        "path": null,
                                        "width": 750,
                                        "height": 750,
                                        "size": 90.82,
                                        "url": "/uploads/medium_eleven_463d3b72f9.jpg"
                                    },
                                    "small": {
                                        "name": "small_eleven.jpg",
                                        "hash": "small_eleven_463d3b72f9",
                                        "ext": ".jpg",
                                        "mime": "image/jpeg",
                                        "path": null,
                                        "width": 500,
                                        "height": 500,
                                        "size": 44.62,
                                        "url": "/uploads/small_eleven_463d3b72f9.jpg"
                                    }
                                },
                                "hash": "eleven_463d3b72f9",
                                "ext": ".jpg",
                                "mime": "image/jpeg",
                                "size": 153.4,
                                "url": "/uploads/eleven_463d3b72f9.jpg",
                                "previewUrl": null,
                                "provider": "local",
                                "provider_metadata": null,
                                "createdAt": "2022-08-11T01:02:14.523Z",
                                "updatedAt": "2022-08-11T01:02:14.523Z"
                            }
                        }
                    ]
                }
            }
        },
        ...