API 데이터 가져오기

김재즈·2023년 12월 2일
2
post-thumbnail

API 받아오기 지긋지긋하다.


시작

저번 글에서 음악 API를 받아오는 코드를 짰었다.

코드 리뷰

조금의 코드 수정을 해줬고,
원하는 유형의 노래를 원하는 만큼 받아올 수 있게 되었다.


// MusicView.tsx

import { useQuery } from 'react-query';

interface MusicResult {
  trackId: number;
  trackName: string;
}

interface MusicData {
  results: MusicResult[];
}

interface CategoryProps {
  Item: {
    type: string;
    limit: number;
  };
}

const MusicView: React.FC<CategoryProps> = ({ Item }) => {
  const { data, isLoading, error } = useQuery<MusicData, Error>(
    ['musicData', Item.type, Item.limit],
    () =>
      fetch(
        `https://itunes.apple.com/search?term=${encodeURIComponent(
          Item.type
        )}&limit=${Item.limit}&kind=song&wrapperType=track`
      ).then((res) => res.json())
  ); // props로 받아온 type, limit를 API주소에 적용해 맞는 데이터를 가져와 JSON파싱.

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      {data?.results.map((result) => ( // map을 이용해 받아온 모든 데이터 제목 출력
        <div key={result.trackId}>{result.trackName}</div>
      ))}
    </div>
  );
};

export default MusicView;

// Home.tsx

import MusicView from '../component/MusicView';

export default function Home() {

  return (
    <div>
      <MusicView Item={{type: 'pop', limit: 10}} />
      <h1>Home</h1>
    </div>
  );
}

위 코드의 결과는

이렇게 데이터를 받아올 수는 있었다.


문제점

그렇지만 내가 원한건 이게 아니라고!

props를 뒤져봤지만, 앨범 커버 사진이나 가사를 데이터로 받아볼 수 없었다.

해결책

  1. 스포티파이 API

하지만 해당 API를 사용하려니 토큰이니 뭐니 할게 너무 많다.

스포티파이 API에 접근하기 위한 액세스 토큰을 넣어주어야 한다.
이 토큰을 얻기 위해서는 Spotify for Developers에서 애플리케이션을 등록하고,
해당 애플리케이션에서 액세스 토큰을 발급받아 사용하셔야 했다.

너무 복잡하다. 패스

  1. deezer API

일단 위 API를 적용해볼까 하는데, 생각보다 복잡하다.

왜 이렇게 세상에는 쉬운게 없냐.

이미지 제공 X 패스

  1. Last.fm API

앨범 이미지, 가사를 무료로 제공한다는 소식이 있다.
API 키만 발급 받으면 공짜로 사용이 가능하다니!
바로 사용해보도록 하자

일단 해당 API를 사용해서 코드를 작성해봤다.

대안

import { useQuery } from 'react-query';

interface Track {
  id: number;
  title: string;
  artist: string;
  imageUrl: string;
  lyrics?: string;
}

interface SearchQuery {
  type: string;
  limit: number;
}

const fetchTracks = async (query: SearchQuery) => {
  const lastFmApiKey = '8fd24dd2138b6432806d59253a8ab108'; 
  const response = await fetch(
    `https://ws.audioscrobbler.com/2.0/?method=track.search&track=${query.type}&limit=${query.limit}&api_key=${lastFmApiKey}&format=json`
  );

  if (!response.ok) {
    throw new Error('Network response was not ok');
  }

  const data = await response.json();
  console.log(data.results);
  return data.results.trackmatches.track.map((item: any) => ({
    id: item.mbid,
    title: item.name,
    artist: item.artist,
    imageUrl: item.image[1]['#text'],
  }));
};

const MusicView: React.FC<{ query: SearchQuery }> = ({ query }) => {
  const { data, isLoading, error } = useQuery(['tracks', query], () => fetchTracks(query));

  console.log(data);

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error</div>;
  }

  return (
    <div>
      {data.map((track: Track) => (
        <div key={track.id}>
          <img src={track.imageUrl} alt="Album Cover" />
          <div>{track.title}</div>
          <div>{track.artist}</div>
        </div>
      ))}
    </div>
  );
};

export default MusicView;


참 좋긴 한데, 이미지가 안나와서 찾아보니

해당 API 사이트도 이미지 제공을 안한답니다~! ㅋㅋ

결국에는 스포티파이 API를 사용하는 것으로 하고..
힘이 드니,,

다음 시간에 다시 해보도록 할게요..

profile
개발의 천재

1개의 댓글

comment-user-thumbnail
2023년 12월 4일
답글 달기