Skip to content

Instantly share code, notes, and snippets.

@wooramy
Last active October 15, 2023 08:57
Show Gist options
  • Save wooramy/c081f171f0227fa9f8a86d590dc30e7f to your computer and use it in GitHub Desktop.
Save wooramy/c081f171f0227fa9f8a86d590dc30e7f to your computer and use it in GitHub Desktop.
Naver Papago Translation API via Axios (Axios를 활용한 네이버 파파고 번역 API 예제 )
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();
@wooramy
Copy link
Author

wooramy commented Feb 3, 2019

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.

[nmt] Hi, Uram. Nice to meet you.
[smt] Hi, Uram. Good to see you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment