발급받은 API 키는 추후 API를 요청할 때 API 주소의 쿼리 파라미터로 넣어서 사용하자.
아래의 주소에서 API에 대한 정보를 확인할 수 있다.
https://newsapi.org/s/south-korea-news-api
사용할 API 주소의 형태는 다음과 같다.
전체 뉴스 불러오기
GET https://newsapi.org/v2/top-headlines?country=kr&apiKey=0a8c4202385d4ec1bb93b7e277b3c51f
특정 카테고리 뉴스 불러오기
GET https://newsapi.org/v2/top-headlines?country=kr&category=business&apiKey=0a8c4202385d4ec1bb93b7e277b3c51f
카테고리는 business, entertainment, health, science, sports, technology 중에 골라서 사용할 수 있다. 카테고리 생략시 모든 카테고리의 뉴스가 불러온다.
apiKey값에는 발급받은 key값을 넣자.
import React, { useState } from "react";
import axios from "axios";
function App() {
const [data, setData] = useState(null);
const onClick = async () => {
try {
const response = await axios.get(
"https://newsapi.org/v2/top-headlines?country=kr&apiKey=0a8c4202385d4ec1bb93b7e277b3c51f"
);
setData(response.data);
} catch (e) {
console.log(e);
}
};
return (
<div>
<div>
<button onClick={onClick}>불러오기</button>
</div>
{data && (
<textarea
rows={7}
value={JSON.stringify(data, null, 2)}
readOnly={true}
/>
)}
</div>
);
}
export default App;
잘 뜨는 것을 확인할 수 있다.