코딩일상
NewsApi를 이용하여 기사데이터 가져오기(feat. node.js) 본문
입사 면접 과제로 NewsApi를 이용하여 프로젝트를 만들면서 NewsApi 사용법에 대해 정리해보려고 한다.
이 API를 통해서 하니 정말 쉽게 전세계 곳곳의 News를 쉽게 가져올수 있어서 좋았다.
NewsApi 소개
api명답게 news정보를 가져올수 있는 open api 이다.
News API – Search News and Blog Articles on the Web
“Ascender AI has a mission to apply AI to the media, and NewsAPI is one of our most valuable resources. Ascender is redefining how users interact with complex information, and the NewsAPI feed is an essential showcase for our technologies.” Braddock Ga
newsapi.org
1)접근 API key키 발급받기
우선 시작을 하려면 API key가 필요하다. 위 홈페이지 링크를들어가서 Get API Key를 누르면 쉽게 얻을수있다.
위과정을 통해 키를 얻었다고 치면 아래와 같은 API 접근 키를 얻을 수있다.
2)요청 보내는방법
//GET 요청
https://newsapi.org/v2/top-headlines?country=kr&apiKey=70ee44584d0b440c8792518dd25119ef
예시)<GET 요청> apiKey='발급받은 APIKey'를 넣고 위 경로로 요청하면 Top articles from South Korea가 나온다.
참고 링크: https://newsapi.org/s/south-korea-news-api
South Korea News API - Live top articles from South Korea
Search live top and breaking news articles 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 articles from South Korea. Top art
newsapi.org
추가로 카테고리별로 Top articles from South Korea를 할수있는데 카테고리를 추가 할 경우에는
//GET 요청
https://newsapi.org/v2/top-headlines?country=kr&category=business&apiKey=70ee44584d0b440c8792518dd25119ef
한국의 Top articles 이면서 카테고리가 business인경우 "country=kr&category=business"를 추가 하면된다.
Newapi 라이브러리
저자의 경우는 이를 백엔드단에서 이용를 해라는 과제를 받아서 좀더 공식문서를 파악하는 도중에 Newapi라이브러리가 있길래 이를 사용하였다.(개인적으로 이를 사용하는것이 더 직관적이어서 좋았다.)
NPM
$ npm install newsapi --save
const NewsAPI = require('newsapi');
const newsapi = new NewsAPI('70ee44584d0b440c8792518dd25119ef');
// To query /v2/top-headlines
// All options passed to topHeadlines are optional, but you need to include at least one of them
newsapi.v2.topHeadlines({
sources: 'bbc-news,the-verge',
q: 'bitcoin',
category: 'business',
language: 'en',
country: 'us'
}).then(response => {
console.log(response);
/*
{
status: "ok",
articles: [...]
}
*/
});
위 코드에 대해 간략히 소개를 해드리자면 아래와 같다.
기사데이터를 가져오기위한 조건
const newsapi = new NewsAPI('발급받은 API 키 입력');
기사 데이터를 가져오는것에 대한 찾기 옵션들
sources: 기사가 나온 곳에대해
q: 기사를 검색할 키워드
category: 기사 카테고리
language: 기사에서 사용되어지는 언어
country: 기사가 나온 나라
이런식으로 하나의 주소가 아니라 옵션별로 따로따로 한눈에 볼수있어 코드의 가독성이 더좋다고 느껴서 이 라이브러리를 사용했다.
더자세한 내요은 아래 링크를 들어가보면된다.
Node.js client library - News API
Node.js client library Use the unofficial Node.js client library to integrate News API into your Node.js application without having to make HTTP requests directly. Source: bzarras/newsapi Installation $ npm install newsapi --save Usage const NewsAPI = requ
newsapi.org
적용예시 한부분으로 기사가 하나도 없을 경우 아래 결과 값과 같이 totalResults 가 0일경우를 만들어서 적용하기도하였다.
....
const response = await newsapi.v2.topHeadlines({
category: "business",
country: "kr",
});
const articleCounts = response.totalResults;
//해당하는 기사가 없을 경우 기사가 없다가 없다고 400 응답 메세지 보내기
if (articleCounts === 0) {
res.status(400).json({
success: false,
errorMessage: "기사가 없습니다.",
});
}
....
저자의 경우에는 NewAPi라이브러리를 사용했지만 이 방법외에
백엔드단에서 응답값을 받아서 활용을 해보고 싶다면,
node-fetch를 써보는것도 하나의 방법이라고 생각한다.
이에 대한 자세한 방법은 아래 링크를 참고하면 좋을것같습니다.
사실 처음에는 이 블로그를 통해 하다가 공식문서에 라이브러가 있다는것을 발견해서 저는 라이브러리로 진행했습니다.
node-fetch
A light-weight module that brings Fetch API to node.js. Latest version: 3.2.10, last published: 3 months ago. Start using node-fetch in your project by running `npm i node-fetch`. There are 28004 other projects in the npm registry using node-fetch.
www.npmjs.com
JS) Fetch함수와 NewsApi 사용하기
활용할 기능적 내용은 JS의 fetch함수와, NewsApiNewsApi : https://newsapi.org/우선 https://newsapi.org/ 사이트에 접속해Get API Key로 회원가입, api key얻는다. 이따가 이거 써야하니 잘
velog.io
'기록 > TIL(Today I Learned)' 카테고리의 다른 글
[TypeScript] 오늘의 공부 정리 (0) | 2022.11.01 |
---|---|
TypeScript는 왜 써야할까?? 공부시작!!! (0) | 2022.10.28 |
22.09.17 TIL 서비스에 맞는 DB 설계란 과연 무엇일까?? 이게 과연 최선일까?? (0) | 2022.09.17 |
22.09.12 TIL 불편함나를 움직이고 움직임이 끝이없다... (0) | 2022.09.13 |
22.08.19 TIL 클론 코딩!! 실전프로젝트전 마지막 주차!! (0) | 2022.08.20 |