Programming/Node.js

날씨 API (Openweather API) 이용하여 날씨 데이터(JSON) 파싱

SiriusJ 2016. 7. 3. 22:42
반응형

날씨 API는 많이 지원해주고 있습니다.

기상청API나 기타 다른 API들도 있지만 그 중에서도 저는 이번에 Openweather라는 날씨 API를 이용해보려 합니다.

(저는 Node.js를 이용한 서버에서 JSON 형식의 데이터로 파싱해오도록 하겠습니다.)


먼저 http://www.openweathermap.org/ 으로 접속해봅시다.


상단 메뉴에서 API를 클릭하면 아래와 같이 보실 수 있습니다.

먼저, API Key를 클릭하여 해당 페이지로 이동하고, Sign up을 하여 API KEY를 얻어줍시다.

(API를 사용하기 위해 얻어진 API KEY는 꼭 기억해주셔야 합니다!)


이후에 Current weather data 의 API doc을 클릭하여 문서를 참조하면, API를 이용하는 부분에 대한 설명을 확인할 수 있습니다. API를 이용하는 중요한 정보들이 대부분 이곳에 있으므로 자주 참조하게 될 것입니다.


만약, API KEY를 얻었다면, 아래에서 APPID=  다음에 받으신 API KEY를 그대로 넣어서 브라우저에서 접속해보면, 현재 서울의 기상정보를 JSON형식의 데이터로 바로 확인할 수 있습니다.

http://api.openweathermap.org/data/2.5/weather?q=Seoul&mode=json&units=metric&APPID=(당신의KEY를넣어주세요.)

(크롬 브라우저에서의 URL을 이용한 날씨정보 확인 - 참고)

여기까지, 만약 브라우저에서 해당 url로 접속했을 때 다음과 같이 데이터가 보이지 않는다면 API KEY가 잘못되었을 확률이 높으므로 다시한번 확인해줍시다!


만약, 잘 확인이 되었다면, 이제 자신의 서버에서 직접 서버에 요청을 보내어 위와 같은 데이터를 가져와야 합니다.

아래 코드에서 URL에 APPID에 자신의 APPKEY만 수정해서 넣어주시면 됩니다.

///////////////////////////////////////////////////////////////////////////////////////////////////////////////

[testServer.js]

var http = require('http');

var express = require('express');


var app = express();

var server = http.createServer(app);


app.use(express.static(__dirname + "/index"));


app.get('/', function(req, res, err) {

res.send(200, "Success");

});


//(Temp variable), for Weather Information

var cityname, citylon, citylat, cityweather, weatherid, weathermain, citytemp, cityhumi, citytemp_min, citytemp_max, citywind, cityclouds;

//var weatherArr = new Array();            아래에서 변수에 저장하는 대신 배열을 이용하셔도 됩니다.


//(Temp variable2), for Today weather Information

var citytime9, citytemp9, cityhumi9, citymain9, cityid9;

var citytime12, citytemp12, cityhumi12, citymain12, cityid12;

var citytime15, citytemp15, cityhumi15, citymain15, cityid15;

var citytime18, citytemp18, cityhumi18, citymain18, cityid18;

var citytime21, citytemp21, cityhumi21, citymain21, cityid21;


//현재시간에 맞는 서울의 날씨정보를 얻어오는 function입니다.

function currentInfo() {

var urlCurr = 'http://api.openweathermap.org/data/2.5/weather?q=Seoul&mode=json&units=metric&APPID=당신의API키를넣어주세요.';


http.get(urlCurr, function(res) {

var body = '';

res.on('data', function(chunk) {

body += chunk.toString();

});


res.on('end', function() {

try {

var fbResponse = JSON.parse(body);    

//JSON형식으로 추출하여 fbResponse에 담아주고, 아래에서 각각의 변수들에 해당 데이터를 저장해 줍니다.


cityname = fbResponse.name;        //도시 이름

citylon = fbResponse.coord.lon;      //도시의 좌표(경도,위도)

citylat = fbResponse.coord.lat;

weatherid = fbResponse.weather[0].id;

weathermain = fbResponse.weather[0].main;

citytemp = fbResponse.main.temp;

cityhumi = fbResponse.main.humidity;

citytemp_min = fbResponse.main.temp_min;

citytemp_max = fbResponse.main.temp_max;

citywind = fbResponse.wind.speed;

cityclouds = fbResponse.clouds.all;

//아래에서 로그를 콘솔에 찍어봄으로써 데이터가 제대로 추출되었는지 확인해봅니다.

console.log("cityname=", cityname);

console.log("weatherid=", weatherid);

console.log("weathermain=", weathermain);

console.log("citytemp=", citytemp);

} catch (e) {

console.log(e);

/* 가끔씩, 한번에 못 받아올때가 있습니다. (아마 서버쪽의 오류인듯 싶습니다.) 그래서 만약 못받아 올 때를 대비하여 try-catch구문을 이용하여 catch에서 currentInfo()를 한번 더 선언해줌으로써 오류가 났을 때에는 다시 한번 요청을 해서 받아오게 됩니다. */

currentInfo();

}

});

res.on('error', function(e) {

console.log("Got an error: ", e);

});

});

}

//Active Once. (First) - 서버를 실행할 때, currentInfo()를 불러주어 아래에서 API를 처음 call하게 됩니다.

currentInfo();

//After, repeat Active (After), - (period 1Hour, for update) - 이후에, 1시간 간격으로 Interval을 통하여 지속적으로 실행해줍니다.

var curi = setInterval(currentInfo, 3600000);



/*아래의 todayInfo()는 현재 시간에 따른 날씨정보 뿐만 아니라 오늘의 날씨정보를 얻기 위하여 추가로 작성해보았습니다.*/

// request for today(forecast) -  위의 currentInfo()와 같은 내용이므로 자세한 설명은 생략하도록 하겠습니다.

function todayInfo() {

var urltoday = 'http://api.openweathermap.org/data/2.5/forecast?q=Seoul&mode=json&units=metric&APPID=당신의API키를넣어주세요.';

http.get(urltoday, function(res) {

var body2 = '';

res.on('data', function(chunk2) {

body2 += chunk2.toString();

});


res.on('end', function() {

try {

var fbResponse2 = JSON.parse(body2);


citytemp9 = fbResponse2.list[0].main.temp;

cityhumi9 = fbResponse2.list[0].main.humidity;

cityid9 = fbResponse2.list[0].weather[0].id;

citymain9 = fbResponse2.list[0].weather[0].main;

citytemp12 = fbResponse2.list[1].main.temp;

cityhumi12 = fbResponse2.list[1].main.humidity;

cityid12 = fbResponse2.list[1].weather[0].id;

citymain12 = fbResponse2.list[1].weather[0].main;


citytemp15 = fbResponse2.list[2].main.temp;

cityhumi15 = fbResponse2.list[2].main.humidity;

cityid15 = fbResponse2.list[2].weather[0].id;

citymain15 = fbResponse2.list[2].weather[0].main;


citytemp18 = fbResponse2.list[3].main.temp;

cityhumi18 = fbResponse2.list[3].main.humidity;

cityid18 = fbResponse2.list[3].weather[0].id;

citymain18 = fbResponse2.list[3].weather[0].main;


citytemp21 = fbResponse2.list[4].main.temp;

cityhumi21 = fbResponse2.list[4].main.humidity;

cityid21 = fbResponse2.list[4].weather[0].id;

citymain21 = fbResponse2.list[4].weather[0].main;

console.log("citymain in 9(Morning)=", citymain9);

console.log("citymain in 21(Evening)=", citymain9);

} catch (e) {

console.log(e);

todayInfo();

}

});

res.on('error', function(e) {

console.log("Got an error: ", e);

});

});

}

todayInfo();

var todayI = setInterval(todayInfo, 86400000); //86400sec = 1 day,(period 1day, for update)


server.listen(8888, function(req, res) {

console.log("server running on 8888.");

});


///////////////////////////////////////////////////////////////////////////////////////////////////////////////

이해를 돕기위하여 변수를 무지막지하게 선언했습니다...

변수들 대신에 배열을 만들어서 원하는 데이터를 추출하셔도 됩니다.

ex) var weatherArr[];

와 같이 선언 후, 배열에 파싱한 값을 넣어주셔도 됩니다.


이상으로, GET방식으로 서버에 요청하여 JSON 형식의 데이터를 받아오는 모습이었습니다.


위 코드를 작성하고 실행시키면, 아래와 같이 데이터가 콘솔에 찍히는 것을 확인 할 수 있습니다.

(워낙에 설명이 빈약해서.. 참고 설명으로 cityname은 url에서 요청한 도시에 대한 이름이, weatherid는 Open weather API에서 지정한 날씨Code가, weathermain은 날씨의 정보가, citytemp는 도시의 온도 정보 입니다.!)


보다 구체적인 데이터들을 확인하고, 파싱하고 싶다면 문서를 참조하시는걸 추천드립니다! 또한 서울 뿐만이 아니라 URL에서 Seoul 대신 다른 도시로 바꿔주어 해당 도시에 대한 정보를 얻을 수 있습니다. Open weather에서 제공하는 도시의 목록은 http://www.openweathermap.org/current 부분을 열심히 뒤져보시면 어딘가에 도시 Sample들에 대한 파일이 있을겁니다. 받으셔서 도시들 목록을 확인하시면 됩니다. (우리나라 뿐만 아니라 세계 각국의 도시들도 무지 많습니다.)

http://bulk.openweathermap.org/sample/ )

반응형