이전 글
1. newsAPI 키 발급받기
먼저 아래의 사이트에 접속하여 회원가입을 진행한다.
Register - News API
Email addresses will be verified, please enter a real one. Disposable addresses have been blocked. Reminder: If you are a business or are using News API commercially then a subscription is required to continue using the API outside of development.
newsapi.org
회원가입에 성공하면 아래와 같은 화면이 노출된다.
발급받은 API 키는 나중에 API 호출시에 필요한 Key 값이다.
2. newsAPI 공식문서/사용 API
아래의 링크에 들어가면 한국 뉴스에 대한 API 설명서를 확인 할 수 있다.
South Korea News API - Live top headlines from South Korea
Get live top and breaking news headlines from South Korea with our JSON API. Live example This example demonstrates the HTTP request to make, and the JSON response you will receive, when you use the News API to get live headlines from South Korea. Top head
newsapi.org
아래와 같이 두가지 타입의 API를 사용할 예정이다.
- 전체뉴스 가져오기
GET : https://newsapi.org/v2/top-headlines?country=kr&apiKey=afda249a1ccb482fa0944d12a295021b - 특정 카테고리 뉴스 가져오기GET : https://newsapi.org/v2/top-headlines?country=kr&category=business&apiKey=afda249a1ccb482fa0944d12a295021b
3. newsAPI 사용코드/결과
이전글에 작성한 App.js API를 발급받은 API로 교체하자.
- App.js
import React, { useState } from 'react';
import axios from 'axios';
const App = () => {
// API를 넘겨받을 state 선언
const [data, setData ] = useState(null);
const onClick = async () => {
// axios 라이브러리로 apic call
try {
const response = await axios.get(
'https://newsapi.org/v2/top-headlines?country=kr&apiKey=afda249a1ccb482fa0944d12a295021b',
);
// 응답 data state 저장
setData(response.data);
} catch (e) {
console.log(e)
}
};
return (
<div>
<div>
<button onClick={() => onClick()}>불러오기</button>
</div>
{/* JSON 문자열 뿌릴 영역 */}
{data && <textarea rows={7} value={JSON.stringify(data, null, 2)} readOnly={true} />}
</div>
);
};
export default App
- 화면 결과
아래와 같이 API가 호출되면 성공이다.
'프론트엔드 > React' 카테고리의 다른 글
[프론트엔드] REACT 뉴스 뷰어 만들기 [5] (0) | 2022.03.25 |
---|---|
[프론트엔드] REACT 뉴스 뷰어 만들기 [4] (0) | 2022.03.24 |
[프론트엔드] REACT 뉴스 뷰어 만들기 [2] (0) | 2022.03.23 |
[프론트엔드] REACT 뉴스 뷰어 만들기 [1] (0) | 2022.03.22 |
[프론트엔드] react router v6 NavLink (0) | 2022.03.21 |