Available in Classic and VPC
These are implementation examples for retrieving blog search results from NAVER Search using the Search API. Since the process for implementing other Search API operations is similar, you can use these examples as a reference to implement the Search API.
- In the sample code, enter the client ID issued by the NAVER Cloud Platform console into
YOUR_CLIENT_ID, and the client secret mapped to that client ID intoYOUR_CLIENT_SECRET. - See the instructions on how to obtain a client ID and client secret in NAVER API HUB overview.
Get blog search result
This section describes an example of Search API that retrieves blog search results from NAVER Search. By replacing the request URI (/search/v1/blog) and query parameters (such as query and display) with values for other search operations, you can retrieve different search results in the same way.
Java
The following is a Java-based sample code for the API.
package com.naver.apihub.example;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class ApiExampleSearchBlog {
public static void main(String[] args) {
String clientId = "YOUR_CLIENT_ID"; // Application's client ID
String clientSecret = "YOUR_CLIENT_SECRET"; // Application's client secret
String text;
try {
text = URLEncoder.encode("Coffee", "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Search keyword encoding failed", e);
}
String apiUrl = "https://naverapihub.apigw.ntruss.com/search/v1/blog?query=" + text + "&display=2";
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("X-NCP-APIGW-API-KEY-ID", clientId);
requestHeaders.put("X-NCP-APIGW-API-KEY", clientSecret);
String responseBody = get(apiUrl, requestHeaders);
System.out.println(responseBody);
}
private static String get(String apiUrl, Map<String, String> requestHeaders) {
HttpURLConnection con = connect(apiUrl);
try {
con.setRequestMethod("GET");
for (Map.Entry<String, String> header : requestHeaders.entrySet()) {
con.setRequestProperty(header.getKey(), header.getValue());
}
int responseCode = con.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // Normal response
return readBody(con.getInputStream());
} else { // Error response
return readBody(con.getErrorStream());
}
} catch (IOException e) {
throw new RuntimeException("API request and response failed", e);
} finally {
con.disconnect();
}
}
private static HttpURLConnection connect(String apiUrl) {
try {
URL url = new URL(apiUrl);
return (HttpURLConnection) url.openConnection();
} catch (MalformedURLException e) {
throw new RuntimeException("Invalid API URL. : " + apiUrl, e);
} catch (IOException e) {
throw new RuntimeException("Connection failed. : " + apiUrl, e);
}
}
private static String readBody(InputStream body) {
InputStreamReader streamReader = new InputStreamReader(body, StandardCharsets.UTF_8);
try (BufferedReader lineReader = new BufferedReader(streamReader)) {
StringBuilder responseBody = new StringBuilder();
String line;
while ((line = lineReader.readLine()) != null) {
responseBody.append(line);
}
return responseBody.toString();
} catch (IOException e) {
throw new RuntimeException("Failed to read the API response.", e);
}
}
}
PHP
The following is a PHP-based sample code for the API.
<?php
$client_id = "YOUR_CLIENT_ID";
$client_secret = "YOUR_CLIENT_SECRET";
$enc_text = urlencode("Coffee");
$url = "https://naverapihub.apigw.ntruss.com/search/v1/blog?query=" . $enc_text . "&display=2";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = array();
$headers[] = "X-NCP-APIGW-API-KEY-ID: " . $client_id;
$headers[] = "X-NCP-APIGW-API-KEY: " . $client_secret;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($status_code == 200) {
echo $response;
} else {
echo "Error content:" . $response;
}
?>
Node.js
The following is a Node.js-based sample code for the API.
const client_id = 'YOUR_CLIENT_ID';
const client_secret = 'YOUR_CLIENT_SECRET';
const api_url =
'https://naverapihub.apigw.ntruss.com/search/v1/blog?query=' +
encodeURIComponent('Coffee') +
'&display=2';
(async () => {
const response = await fetch(api_url, {
headers: {
'X-NCP-APIGW-API-KEY-ID': client_id,
'X-NCP-APIGW-API-KEY': client_secret,
},
});
console.log(response.status);
console.log(await response.text());
})();
Python
The following is a Python-based sample code for the API.
import urllib.request
import urllib.parse
client_id = "YOUR_CLIENT_ID"
client_secret = "YOUR_CLIENT_SECRET"
enc_text = urllib.parse.quote("Coffee")
url = "https://naverapihub.apigw.ntruss.com/search/v1/blog?query=" + enc_text + "&display=2"
request = urllib.request.Request(url)
request.add_header("X-NCP-APIGW-API-KEY-ID", client_id)
request.add_header("X-NCP-APIGW-API-KEY", client_secret)
response = urllib.request.urlopen(request)
rescode = response.getcode()
if rescode == 200:
response_body = response.read()
print(response_body.decode("utf-8"))
else:
print("Error Code:" + str(rescode))
C#
The following is a C#-based sample code for the API.
using System;
using System.IO;
using System.Net;
using System.Text;
namespace NaverApiHubExample
{
public class ApiExampleSearchBlog
{
static void Main(string[] args)
{
string clientId = "YOUR_CLIENT_ID";
string clientSecret = "YOUR_CLIENT_SECRET";
string query = WebUtility.UrlEncode("Coffee");
string url = "https://naverapihub.apigw.ntruss.com/search/v1/blog?query=" + query + "&display=2";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("X-NCP-APIGW-API-KEY-ID", clientId);
request.Headers.Add("X-NCP-APIGW-API-KEY", clientSecret);
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
Console.WriteLine(reader.ReadToEnd());
}
}
catch (WebException e) // Error response
{
using (StreamReader reader = new StreamReader(e.Response.GetResponseStream(), Encoding.UTF8))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
}
}