Last active
October 15, 2023 08:57
-
-
Save wooramy/c081f171f0227fa9f8a86d590dc30e7f to your computer and use it in GitHub Desktop.
Naver Papago Translation API via Axios (Axios를 활용한 네이버 파파고 번역 API 예제 )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const axios = require('axios'); | |
const qs = require('querystring'); | |
const TRANSLATE_METHODS = { | |
nmt: 'nmt', | |
smt: 'smt', | |
}; | |
class Papago { | |
constructor(config) { | |
this.config = config; | |
} | |
async lookup(term, { method }) { | |
if (this.config == null) { | |
throw new Error('Papago instance should be initialized with config first'); | |
} if (term == null) { | |
throw new Error('Search term should be provided as lookup arguments'); | |
} | |
const url = method === TRANSLATE_METHODS.smt ? | |
'language/translate' : 'papago/n2mt'; | |
const params = qs.stringify({ | |
source: 'ko', | |
target: 'en', | |
text: term, | |
}); | |
const config = { | |
baseURL: 'https://openapi.naver.com/v1/', | |
headers: { | |
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', | |
'x-naver-client-id': this.config.NAVER_CLIENT_ID, | |
'x-naver-client-secret': this.config.NAVER_CLIENT_SECRET, | |
}, | |
}; | |
const response = await axios.post(url, params, config); | |
return response.data.message.result.translatedText; | |
} | |
} | |
async function main() { | |
// NOTE: populate with your own Client id/secret from https://developers.naver.com/apps | |
const papago = new Papago({ | |
NAVER_CLIENT_ID: '', | |
NAVER_CLIENT_SECRET: '', | |
}); | |
const nmtResult = await papago.lookup('안녕, 우람. 반가워.', { method: 'nmt' }); | |
console.log('[nmt]', nmtResult); | |
const smtResult = await papago.lookup('안녕, 우람. 반가워.', { method: 'smt' }); | |
console.log('[smt]', smtResult); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tried using axios instead of request as used in the official API documentation, but I fumbled upon 'content-type' and param handling and here's the sample code.
Below is the console log on successful run.