### Build with Installed Maven Source: https://github.com/naver/searchad-apidoc/blob/master/java-sample/README.md Build the Java sample project using a locally installed Maven instance. ```bash $ mvn clean package ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/naver/searchad-apidoc/blob/master/python-sample/README.md Clone the searchad-apidoc repository and install the required Python packages using pip. ```bash $ git clone https://github.com/naver/searchad-apidoc.git $ cd searchad-apidoc/python-sample/ $ pip install -r requirements.txt $ cd examples/ ``` -------------------------------- ### Make a GET Request to Campaigns Endpoint Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/00-START-HERE.md Example of making a GET request to the campaigns endpoint using the 'requests' library. This snippet demonstrates how to construct the headers, including the API key, customer ID, timestamp, and the generated signature. ```python import requests headers = { 'X-API-KEY': 'your_api_key', 'X-Customer': 'your_customer_id', 'X-Timestamp': str(int(time.time() * 1000)), 'X-Signature': get_signature(...), } response = requests.get( 'https://api.searchad.naver.com/ncc/campaigns', headers=headers ) ``` -------------------------------- ### Python SearchAd API Client and Request Example Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/README.md This Python code defines a client for the SearchAd API, including authentication using HMAC-SHA256 signatures. It demonstrates how to initialize the client and make a GET request to retrieve campaigns. ```python import requests import time import hashlib import hmac import base64 class SearchAdClient: def __init__(self, api_key, secret_key, customer_id): self.api_key = api_key self.secret_key = secret_key self.customer_id = customer_id def request(self, method, path, params=None, json=None): timestamp = str(int(time.time() * 1000)) signature = self._sign(timestamp, method, path) headers = { 'X-API-KEY': self.api_key, 'X-Customer': str(self.customer_id), 'X-Timestamp': timestamp, 'X-Signature': signature, 'Content-Type': 'application/json; charset=UTF-8' } url = f'https://api.searchad.naver.com{path}' if method == 'GET': return requests.get(url, params=params, headers=headers).json() elif method == 'POST': return requests.post(url, params=params, json=json, headers=headers).json() elif method == 'PUT': return requests.put(url, params=params, json=json, headers=headers).json() elif method == 'DELETE': return requests.delete(url, params=params, headers=headers) def _sign(self, timestamp, method, path): message = f"{timestamp}.{method}.{path}" h = hmac.new( bytes(self.secret_key, 'utf-8'), bytes(message, 'utf-8'), hashlib.sha256 ) return base64.b64encode(h.digest()).decode('utf-8') # Usage client = SearchAdClient(API_KEY, SECRET_KEY, CUSTOMER_ID) campaigns = client.request('GET', '/ncc/campaigns') ``` -------------------------------- ### Fetch Naver Campaigns Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/README.md This example demonstrates how to fetch all campaigns using the Naver Search Ads API. It requires a base URL, authentication headers, and makes a GET request to the '/ncc/campaigns' endpoint. ```python import requests import json BASE_URL = 'https://api.searchad.naver.com' # Get all campaigns response = requests.get( f'{BASE_URL}/ncc/campaigns', headers=get_auth_headers('GET', '/ncc/campaigns') ) campaigns = response.json() for campaign in campaigns: print(f"{campaign['name']} - Budget: {campaign['dailyBudget']}") ``` -------------------------------- ### Send GET Request with Simple Query Parameters Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/configuration.md Use this snippet to make a GET request with simple key-value query parameters appended to the URL. ```python params = { 'nccCampaignId': campaign_id, 'fields': 'userLock,dailyBudget' } response = requests.get( 'https://api.searchad.naver.com/ncc/adgroups', params=params, headers=headers ) ``` -------------------------------- ### Campaign Management Setup Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/configuration.md Set up a new campaign, including its associated channel and ad group. Returns the IDs for the created campaign, channel, and ad group. ```python def setup_campaign(client, campaign_name, daily_budget, channel_name, site_url): # Create channel channel = client.create_channel(channel_name, site_url) channel_id = channel['nccChannelId'] # Create campaign campaign = client.create_campaign(campaign_name, daily_budget) campaign_id = campaign['nccCampaignId'] # Create ad group adgroup = client.create_adgroup( campaign_id, f"{campaign_name}_AG1", channel_id, channel_id, bid_amount=100 ) return { 'campaign_id': campaign_id, 'channel_id': channel_id, 'adgroup_id': adgroup['nccAdgroupId'] } ``` -------------------------------- ### Setup Authentication Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/00-START-HERE.md Provides a Python code snippet to generate the HMAC-SHA256 signature required for authenticating API requests. ```APIDOC ## Setup Authentication ### Description This section provides a Python code snippet to generate the HMAC-SHA256 signature required for authenticating API requests. The signature is crucial for verifying the identity of the client making the request. ### Method ```python import hashlib, hmac, base64, time def get_signature(timestamp, method, uri, secret_key): message = f"{timestamp}.{method}.{uri}" sig = hmac.new(bytes(secret_key, 'utf-8'), bytes(message, 'utf-8'), hashlib.sha256).digest() return base64.b64encode(sig).decode('utf-8') ``` ### Parameters - **timestamp** (string) - The timestamp of the request in milliseconds. - **method** (string) - The HTTP method of the request (e.g., GET, POST). - **uri** (string) - The URI of the request endpoint. - **secret_key** (string) - Your secret API key. ### Usage Refer to the 'Make Your First Request' section for an example of how to use this function. ``` -------------------------------- ### HTTP Methods for Campaigns Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/00-START-HERE.md Demonstrates common HTTP methods used for managing campaigns. Includes examples for listing, creating, updating, and deleting campaigns. ```text GET /ncc/campaigns - List campaigns POST /ncc/campaigns - Create campaign PUT /ncc/campaigns/{id} - Update campaign DELETE /ncc/campaigns/{id} - Delete campaign ``` -------------------------------- ### Make Your First Request Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/00-START-HERE.md Demonstrates how to make a basic GET request to the Naver Search AD API, including setting up the necessary headers with authentication details. ```APIDOC ## Make Your First Request ### Description This section demonstrates how to make a basic GET request to the Naver Search AD API. It includes setting up the required headers, such as API key, customer ID, timestamp, and the generated signature. ### Method ```python import requests headers = { 'X-API-KEY': 'your_api_key', 'X-Customer': 'your_customer_id', 'X-Timestamp': str(int(time.time() * 1000)), 'X-Signature': get_signature(...), # Assumes get_signature function is defined as above } response = requests.get( 'https://api.searchad.naver.com/ncc/campaigns', headers=headers ) ``` ### Endpoint `https://api.searchad.naver.com/ncc/campaigns` ### Headers - **X-API-KEY** (string) - Your API key. - **X-Customer** (string) - Your customer ID. - **X-Timestamp** (string) - The current timestamp in milliseconds. - **X-Signature** (string) - The signature generated using the `get_signature` function. ### Request Example This example shows a GET request to retrieve campaign details. The headers contain the authentication information. ``` -------------------------------- ### Send JSON Request with Headers and Payload Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/configuration.md This example demonstrates how to construct headers and a JSON payload for a POST request to create a campaign. ```python headers = { 'Content-Type': 'application/json; charset=UTF-8', 'X-API-KEY': API_KEY, 'X-Customer': str(CUSTOMER_ID), 'X-Timestamp': timestamp, 'X-Signature': signature } payload = { 'name': 'Campaign Name', 'dailyBudget': 100000, 'useDailyBudget': True } response = requests.post( 'https://api.searchad.naver.com/ncc/campaigns', json=payload, headers=headers ) ``` -------------------------------- ### Create Ad Group with Channel IDs Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/channels.md Example payload for creating an ad group, demonstrating the requirement to specify both PC and mobile channel IDs. ```Python payload = { 'name': 'My Ad Group', 'nccCampaignId': campaign_id, 'pcChannelId': pc_channel_id, 'mobileChannelId': mobile_channel_id, 'bidAmt': 100 } ``` -------------------------------- ### Retrieve All Campaigns Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/endpoints.md GET endpoint to retrieve all campaigns for the authenticated customer. No query parameters are required. ```http GET /ncc/campaigns ``` -------------------------------- ### GET /customer-links Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/endpoints.md Retrieve customer account relationships, either as a client or a master. ```APIDOC ## GET /customer-links ### Description Retrieve customer account relationships. ### Method GET ### Endpoint /customer-links ### Parameters #### Query Parameters - `type` (string) - Required - "MYCLIENTS" or "MYMASTERS" ### Response #### Success Response (200 OK) - Array of CustomerLink objects ``` -------------------------------- ### Get Stats with Device Breakdown Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/stats.md Retrieve statistics for multiple entities with a breakdown by device type. This helps in understanding performance differences between desktop and mobile users. ```http GET /stats?ids=camp_789&fields=["clkCnt","ctr"]&timeIncrement=allDays&breakdown=pcMblTp&datePreset=last7days ``` -------------------------------- ### Java SearchAd API Client Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/configuration.md A Java class for interacting with the SearchAd API. It includes methods for generating signatures and executing HTTP requests for GET and POST operations. Ensure you have the necessary Unirest and Jackson libraries added to your project. ```java import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import com.fasterxml.jackson.databind.ObjectMapper; public class SearchAdApiClient { private String apiKey; private String secretKey; private long customerId; private String baseUrl = "https://api.searchad.naver.com"; public SearchAdApiClient(String apiKey, String secretKey, long customerId) { this.apiKey = apiKey; this.secretKey = secretKey; this.customerId = customerId; } private String generateSignature(String timestamp, String method, String uri) throws Exception { String message = timestamp + "." + method + "." + uri; byte[] keyBytes = secretKey.getBytes("UTF-8"); byte[] messageBytes = message.getBytes("UTF-8"); javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256"); javax.crypto.spec.SecretKeySpec keySpec = new javax.crypto.spec.SecretKeySpec(keyBytes, "HmacSHA256"); mac.init(keySpec); byte[] hash = mac.doFinal(messageBytes); return java.util.Base64.getEncoder().encodeToString(hash); } private HttpResponse executeRequest(String method, String path, Object body) throws Exception { String timestamp = String.valueOf(System.currentTimeMillis()); String signature = generateSignature(timestamp, method, path); HttpResponse response = null; if ("GET".equals(method)) { response = Unirest.get(baseUrl + path) .header("X-API-KEY", apiKey) .header("X-Customer", String.valueOf(customerId)) .header("X-Timestamp", timestamp) .header("X-Signature", signature) .asString(); } else if ("POST".equals(method)) { response = Unirest.post(baseUrl + path) .header("X-API-KEY", apiKey) .header("X-Customer", String.valueOf(customerId)) .header("X-Timestamp", timestamp) .header("X-Signature", signature) .header("Content-Type", "application/json; charset=UTF-8") .body(new ObjectMapper().writeValueAsString(body)) .asString(); } return response; } } ``` -------------------------------- ### API Reference Overview Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/MANIFEST.txt The Naver Search Ad API offers a RESTful interface for managing advertising campaigns. Documentation is organized by resource, with detailed information on endpoints, parameters, request/response formats, and code examples. ```APIDOC ## API Reference Structure The API reference is organized into the following categories: * **Campaigns**: Manage campaign resources, including CRUD operations, budget, and scheduling. * **Ad Groups**: Structure and manage ad groups, including targeting and targeting rules. * **Keywords**: Manage keyword resources, focusing on bidding, quality index, and approval status. * **Ads**: Define and manage advertisement creatives of all types. * **Channels**: Organize business channels, such as websites. * **Ad Extensions**: Configure ad extension resources like callouts and sitelinks. * **Customer Links**: Manage account relationships. * **Estimate**: Access bid and performance estimation endpoints. * **Stats**: Retrieve performance statistics and reporting data. Each resource page provides complete endpoint signatures, parameter details, request/response examples, and code snippets. ``` -------------------------------- ### Clone the Sample Repository Source: https://github.com/naver/searchad-apidoc/blob/master/php-sample/README.md Clone the Naver SearchAD API PHP sample repository using Git. ```bash $ git clone https://github.com/naver/searchad-apidoc.git $ cd searchad-apidoc/php-sample/ ``` -------------------------------- ### Execute Python Sample on *nix Systems Source: https://github.com/naver/searchad-apidoc/blob/master/python-sample/README.md Run the Python sample script from the command line on Unix-like systems. ```bash $ python ad_management_sample.py ``` -------------------------------- ### Create Campaign, Ad Group, Keyword, and Ad Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/README.md This snippet demonstrates the sequential creation of advertising entities. Ensure the client is initialized before use. ```python # 1. Create Campaign campaign = client.create_campaign( name='My Campaign', daily_budget=100000, delivery_method='STANDARD' ) campaign_id = campaign['nccCampaignId'] # 2. Create Ad Group adgroup = client.create_adgroup( campaign_id=campaign_id, name='My Ad Group', pc_channel_id=channel_id, mobile_channel_id=channel_id, bid_amt=100 ) adgroup_id = adgroup['nccAdgroupId'] # 3. Create Keywords keywords = client.create_keywords( adgroup_id=adgroup_id, keywords=[ {'keyword': 'search term 1', 'bidAmt': 100}, {'keyword': 'search term 2', 'bidAmt': 150} ] ) # 4. Create Ad ad = client.create_ad( adgroup_id=adgroup_id, type='TEXT_AD', ad={ 'headline': 'My Ad Title', 'description': 'My ad description', 'displayUrl': 'example.com', 'landingUrl': 'https://example.com' } ) ``` -------------------------------- ### GET /ncc/adgroups Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/endpoints.md Retrieve a list of ad groups. This can be used to get all ad groups or to filter them by a specific campaign ID. ```APIDOC ## GET /ncc/adgroups Retrieve ad groups, optionally filtered by campaign. **Query Parameters:** - `nccCampaignId` (optional): Filter by campaign ID **Response:** Array of Adgroup objects **Status Codes:** 200 OK ``` -------------------------------- ### Clone the Java Sample Repository Source: https://github.com/naver/searchad-apidoc/blob/master/java-sample/README.md Clone the official Naver SearchAD API Java sample repository and navigate into the project directory. ```bash $ git clone https://github.com/naver/searchad-apidoc.git $ cd searchad-apidoc/java-sample/ ``` -------------------------------- ### Execute Sample Code on *nix Systems Source: https://github.com/naver/searchad-apidoc/blob/master/java-sample/README.md Execute the compiled Java sample code on Unix-like systems, ensuring the classpath includes the JAR and library files. ```bash $ cd target $ java -cp com.naver.searchad.api-java-sample.jar:lib/* com.naver.searchad.api.sample.AdManagementSample ``` -------------------------------- ### GET /ncc/channels Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/endpoints.md Retrieve all channels associated with the customer. ```APIDOC ## GET /ncc/channels ### Description Retrieve all channels for the customer. ### Method GET ### Endpoint /ncc/channels ### Response #### Success Response (200 OK) - Array of Channel objects ``` -------------------------------- ### Get Ad Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/ads.md Retrieves a specific ad by its unique ID. ```APIDOC ## GET /ncc/ads/{nccAdId} ### Description Retrieves a specific ad by ID. ### Method GET ### Endpoint /ncc/ads/{nccAdId} ### Parameters #### Path Parameters - **nccAdId** (string) - Yes - Ad ID to retrieve #### Header Parameters - **X-Customer** (long) - Yes - Customer ID - **X-API-KEY** (string) - Yes - API key - **X-Timestamp** (string) - Yes - Current timestamp - **X-Signature** (string) - Yes - HMAC-SHA256 signature ### Response #### Success Response (200) Returns a single Ad object. #### Response Example ```json { "nccAdId": "string", "type": "string", "ad": {} } ``` ``` -------------------------------- ### GET /ncc/ads/{nccAdId} Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/endpoints.md Retrieve a specific ad by its unique ID. ```APIDOC ## GET /ncc/ads/{nccAdId} ### Description Retrieve a specific ad by ID. ### Method GET ### Endpoint /ncc/ads/{nccAdId} ### Response #### Success Response (200 OK) - Single Ad object #### Error Response (404 Not Found) - Ad not found ``` -------------------------------- ### Execute Ad Management Sample (Windows) Source: https://github.com/naver/searchad-apidoc/blob/master/php-sample/README.md Run the ad management sample script using the PHP command-line interpreter on Windows. ```bat > php.exe -f ad_management_sample.php ``` -------------------------------- ### GET /stats Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/endpoints.md Retrieve performance statistics for entities, with options for date ranges, increments, and breakdowns. ```APIDOC ## GET /stats ### Description Retrieve performance statistics for entities. ### Method GET ### Endpoint /stats ### Parameters #### Query Parameters - `id` (string) - Conditional - Single entity ID - `ids` (string) - Conditional - Comma-separated entity IDs (use either id or ids) - `fields` (string) - Required - JSON array of field names, e.g., `["clkCnt","impCnt","ctr"]` - `timeIncrement` (string) - Required - "1" (daily) or "allDays" (summary) - `datePreset` (string) - Optional - today, yesterday, last7days, last30days, lastweek, lastmonth, lastquarter - `timeRange` (object) - Optional - JSON object: `{"since":"YYYY-MM-DD","until":"YYYY-MM-DD"}` - `breakdown` (string) - Optional - pcMblTp, dayw, hh24, regnNo ### Response #### Success Response (200 OK) - Stat object with DailyStat or SummaryStat depending on timeIncrement #### Error Response (400 Bad Request) ``` -------------------------------- ### Create Campaign, Ad Group, Keyword, and Ad Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/README.md This section demonstrates the process of creating a campaign, followed by an ad group within that campaign, then keywords for the ad group, and finally an ad associated with the ad group. ```APIDOC ## Create Campaign ### Description Creates a new advertising campaign. ### Method `client.create_campaign` ### Parameters - **name** (string) - Required - The name of the campaign. - **daily_budget** (integer) - Required - The daily budget for the campaign. - **delivery_method** (string) - Required - The delivery method for the campaign (e.g., 'STANDARD'). ### Response Returns campaign details including `nccCampaignId`. --- ## Create Ad Group ### Description Creates a new ad group within a specified campaign. ### Method `client.create_adgroup` ### Parameters - **campaign_id** (string) - Required - The ID of the campaign to which the ad group belongs. - **name** (string) - Required - The name of the ad group. - **pc_channel_id** (string) - Required - The channel ID for PC. - **mobile_channel_id** (string) - Required - The channel ID for mobile. - **bid_amt** (integer) - Required - The bid amount for the ad group. ### Response Returns ad group details including `nccAdgroupId`. --- ## Create Keywords ### Description Creates one or more keywords for a specified ad group. ### Method `client.create_keywords` ### Parameters - **adgroup_id** (string) - Required - The ID of the ad group to which the keywords belong. - **keywords** (array of objects) - Required - A list of keywords, where each object contains: - **keyword** (string) - Required - The search term. - **bidAmt** (integer) - Required - The bid amount for the keyword. ### Response Returns details of the created keywords. --- ## Create Ad ### Description Creates a new ad within a specified ad group. ### Method `client.create_ad` ### Parameters - **adgroup_id** (string) - Required - The ID of the ad group to which the ad belongs. - **type** (string) - Required - The type of ad (e.g., 'TEXT_AD'). - **ad** (object) - Required - The ad content, which varies by type. For 'TEXT_AD', it includes: - **headline** (string) - Required - The ad headline. - **description** (string) - Required - The ad description. - **displayUrl** (string) - Required - The display URL. - **landingUrl** (string) - Required - The landing page URL. ### Response Returns details of the created ad. ``` -------------------------------- ### Execute Python Sample on Windows Source: https://github.com/naver/searchad-apidoc/blob/master/python-sample/README.md Run the Python sample script from the command prompt on Windows systems. ```bat > python ad_management_sample.py ``` -------------------------------- ### GET /ncc/ad-extensions Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/endpoints.md Retrieve ad extensions associated with a specific owner (campaign, ad group, or keyword). ```APIDOC ## GET /ncc/ad-extensions ### Description Retrieve ad extensions for an owner. ### Method GET ### Endpoint /ncc/ad-extensions ### Parameters #### Query Parameters - `ownerId` (string) - Required - Owner entity ID (campaign, ad group, or keyword) ### Response #### Success Response (200 OK) - Array of AdExtension objects ``` -------------------------------- ### GET /ncc/campaigns Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/endpoints.md Retrieve all campaigns associated with your customer ID. This endpoint returns an array of campaign objects. ```APIDOC ## GET /ncc/campaigns Retrieve all campaigns for the customer. **Query Parameters:** None **Response:** Array of Campaign objects **Status Codes:** 200 OK ``` -------------------------------- ### Execute Ad Management Sample (Unix) Source: https://github.com/naver/searchad-apidoc/blob/master/php-sample/README.md Run the ad management sample script using the PHP command-line interpreter on Unix-like systems. ```bash $ php -f ad_management_sample.php ``` -------------------------------- ### GET /ncc/ads Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/endpoints.md Retrieve ads, optionally filtered by ad group. Supports filtering by ad group ID. ```APIDOC ## GET /ncc/ads ### Description Retrieve ads, optionally filtered by ad group. ### Method GET ### Endpoint /ncc/ads #### Query Parameters - `nccAdgroupId` (string) - Optional - Filter by ad group ID ### Response #### Success Response (200 OK) - Array of Ad objects ``` -------------------------------- ### Build with Embedded Maven Source: https://github.com/naver/searchad-apidoc/blob/master/java-sample/README.md Build the Java sample project using the embedded Maven wrapper script. ```bash $ ./mvnw clean package ``` -------------------------------- ### Retrieve Ad Groups Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/endpoints.md GET endpoint to retrieve ad groups. Optionally filter by a specific campaign ID. ```http GET /ncc/adgroups?nccCampaignId={nccCampaignId} ``` -------------------------------- ### Get Performance Statistics Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/README.md Retrieves performance statistics for specified entities (campaigns, ad groups) over a given period. ```APIDOC ## Get Performance Statistics ### Description Retrieves performance statistics for specified entities. ### Method `client.get_stats` ### Parameters - **entity_ids** (array of strings) - Required - A list of entity IDs (e.g., campaign IDs, ad group IDs). - **fields** (array of strings) - Required - A list of statistics fields to retrieve (e.g., 'clkCnt', 'impCnt', 'ctr'). - **date_preset** (string) - Optional - A preset date range (e.g., 'last30days'). - **time_increment** (string) - Optional - The time increment for the statistics (e.g., 'daily', 'weekly'). - **time_range** (object) - Optional - A custom time range with 'since' and 'until' dates. - **since** (string) - Required if time_range is used - The start date. - **until** (string) - Required if time_range is used - The end date. ### Response Returns performance statistics for the requested entities and fields. ``` -------------------------------- ### Execute Sample Code on Windows Source: https://github.com/naver/searchad-apidoc/blob/master/java-sample/README.md Execute the compiled Java sample code on Windows systems, ensuring the classpath includes the JAR and library files. ```bat > cd target > java -cp com.naver.searchad.api-java-sample.jar;lib/* com.naver.searchad.api.sample.AdManagementSample ``` -------------------------------- ### TimeRange Inner Class Java Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/types.md Defines a time range for API queries, specifying the start and end dates. ```java public static class TimeRange { private String since; private String until; } ``` -------------------------------- ### HMAC-SHA256 Signature Generation (C#) Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/MANIFEST.txt Example of generating an HMAC-SHA256 signature for API requests in C#. This is required for authentication. ```C# using System; using System.Security.Cryptography; using System.Text; public class SignatureGenerator { // --- Configuration --- private const string CUSTOMER_ID = "YOUR_CUSTOMER_ID"; private const string CUSTOMER_SECRET = "YOUR_CUSTOMER_SECRET"; private const string ACCESS_KEY = "YOUR_ACCESS_KEY"; private const string SECRET_KEY = "YOUR_SECRET_KEY"; public static void Main(string[] args) { // --- Request Details --- string httpMethod = "GET"; string requestUri = "/searchad/v1/campaigns"; long timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // --- Generate Signature --- string message = $"{httpMethod}{requestUri}{timestamp}"; using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(SECRET_KEY))) { byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(message)); string signature = BitConverter.ToString(hashBytes).Replace("-", "").ToLowerInvariant(); // --- Headers --- Console.WriteLine("Headers:"); Console.WriteLine(" Content-Type: application/json"); Console.WriteLine($" X-Timestamp: {timestamp}"); Console.WriteLine($" X-API-KEY: {ACCESS_KEY}"); Console.WriteLine($" X-API-SIGNATURE: {signature}"); Console.WriteLine($" X-Customer-ID: {CUSTOMER_ID}"); } } } ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/configuration.md Configure API keys, customer ID, and base URL for the development environment using environment variables. ```python import os # .env file or environment variables API_KEY = os.getenv('SEARCHAD_API_KEY_DEV') SECRET_KEY = os.getenv('SEARCHAD_SECRET_KEY_DEV') CUSTOMER_ID = int(os.getenv('SEARCHAD_CUSTOMER_ID_DEV')) BASE_URL = 'https://api.searchad.naver.com' LOG_LEVEL = 'DEBUG' ``` -------------------------------- ### Production Environment Configuration Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/configuration.md Configure API keys, customer ID, and base URL for the production environment using a secure secret retrieval method. ```python import os # Use secure credential storage (e.g., AWS Secrets Manager, HashiCorp Vault) API_KEY = get_secret('searchad/api-key') SECRET_KEY = get_secret('searchad/secret-key') CUSTOMER_ID = int(get_secret('searchad/customer-id')) BASE_URL = 'https://api.searchad.naver.com' LOG_LEVEL = 'WARNING' ``` -------------------------------- ### HMAC-SHA256 Signature Generation (Python) Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/MANIFEST.txt Example of generating an HMAC-SHA256 signature for API requests in Python. This is crucial for authentication. ```Python import hashlib import hmac import time # --- Configuration --- CUSTOMER_ID = "YOUR_CUSTOMER_ID" CUSTOMER_SECRET = "YOUR_CUSTOMER_SECRET" ACCESS_KEY = "YOUR_ACCESS_KEY" SECRET_KEY = "YOUR_SECRET_KEY" # --- Request Details --- HTTP_METHOD = "GET" REQUEST_URI = "/searchad/v1/campaigns" TIMESTAMP = str(int(time.time() * 1000)) # --- Generate Signature --- message = f"{HTTP_METHOD}{REQUEST_URI}{TIMESTAMP}" signature = hmac.new(SECRET_KEY.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest() # --- Headers --- headers = { "Content-Type": "application/json", "X-Timestamp": TIMESTAMP, "X-API-KEY": ACCESS_KEY, "X-API-SIGNATURE": signature, "X-Customer-ID": CUSTOMER_ID } print("Headers:", headers) ``` -------------------------------- ### HMAC-SHA256 Signature Generation (Java) Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/MANIFEST.txt Example of generating an HMAC-SHA256 signature for API requests in Java. This is essential for secure authentication. ```Java import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.util.Base64; public class SignatureGenerator { // --- Configuration --- private static final String CUSTOMER_ID = "YOUR_CUSTOMER_ID"; private static final String CUSTOMER_SECRET = "YOUR_CUSTOMER_SECRET"; private static final String ACCESS_KEY = "YOUR_ACCESS_KEY"; private static final String SECRET_KEY = "YOUR_SECRET_KEY"; public static void main(String[] args) throws Exception { // --- Request Details --- String httpMethod = "GET"; String requestUri = "/searchad/v1/campaigns"; long timestamp = System.currentTimeMillis(); // --- Generate Signature --- String message = httpMethod + requestUri + timestamp; Mac sha256_HMAC = Mac.getInstance("HmacSHA256"); SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "HmacSHA256"); sha256_HMAC.init(secretKey); String signature = bytesToHex(sha256_HMAC.doFinal(message.getBytes(StandardCharsets.UTF_8))); // --- Headers --- System.out.println("Headers:"); System.out.println(" Content-Type: application/json"); System.out.println(" X-Timestamp: " + timestamp); System.out.println(" X-API-KEY: " + ACCESS_KEY); System.out.println(" X-API-SIGNATURE: " + signature); System.out.println(" X-Customer-ID: " + CUSTOMER_ID); } private static String bytesToHex(byte[] hash) { StringBuilder hexString = new StringBuilder(2 * hash.length); for (byte b : hash) { String hex = Integer.toHexString(0xff & b); if (hex.length() == 1) { hexString.append('0'); } hexString.append(hex); } return hexString.toString(); } } ``` -------------------------------- ### GET /ncc/adgroups/{nccAdgroupId}/targets Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/endpoints.md Retrieve the targeting strategies associated with a specific ad group. The response is structured by target type. ```APIDOC ## GET /ncc/adgroups/{nccAdgroupId}/targets Retrieve targeting strategies for an ad group. **Query Parameters:** None **Response:** Array of Target objects indexed by target type **Status Codes:** 200 OK ``` -------------------------------- ### Export API Credentials as Environment Variables Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/configuration.md Set your Naver Search AD API key, secret key, and customer ID as environment variables. This is the recommended method for securely storing credentials. ```bash export SEARCHAD_API_KEY="your_api_key" export SEARCHAD_SECRET_KEY="your_secret_key" export SEARCHAD_CUSTOMER_ID="your_customer_id" ``` -------------------------------- ### Get multiple entities summary Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/stats.md Retrieves a summary of statistics for multiple entities, specifying the fields, time increment, and date preset. ```APIDOC ## GET /stats ### Description Retrieves a summary of statistics for multiple entities, specifying the fields, time increment, and date preset. ### Method GET ### Endpoint /stats ### Parameters #### Query Parameters - **ids** (string) - Required - Comma-separated list of entity IDs. - **fields** (array of strings) - Required - List of fields to retrieve (e.g., ["clkCnt","impCnt","ctr"]). - **timeIncrement** (string) - Required - Specifies the time granularity (e.g., "allDays"). - **datePreset** (string) - Required - Specifies a predefined date range (e.g., "last30days"). ### Request Example { "example": "GET /stats?ids=camp_1,camp_2&fields=[\"clkCnt\",\"impCnt\",\"ctr\"]&timeIncrement=allDays&datePreset=last30days" } ``` -------------------------------- ### List Campaigns using Python Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/campaigns.md Retrieves all campaigns associated with the customer account. Requires authentication headers including a generated signature. ```python import requests import time import signaturehelper BASE_URL = 'https://api.searchad.naver.com' API_KEY = 'YOUR_API_KEY' SECRET_KEY = 'YOUR_SECRET_KEY' CUSTOMER_ID = 'YOUR_CUSTOMER_ID' def get_header(method, uri): timestamp = str(round(time.time() * 1000)) signature = signaturehelper.Signature.generate(timestamp, method, uri, SECRET_KEY) return { 'Content-Type': 'application/json; charset=UTF-8', 'X-Timestamp': timestamp, 'X-API-KEY': API_KEY, 'X-Customer': str(CUSTOMER_ID), 'X-Signature': signature } uri = '/ncc/campaigns' method = 'GET' response = requests.get(BASE_URL + uri, headers=get_header(method, uri)) campaigns = response.json() for campaign in campaigns: print(f"Campaign: {campaign['name']} (ID: {campaign['nccCampaignId']})") ``` -------------------------------- ### Get stats with device breakdown Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/stats.md Retrieves statistics for an entity with a breakdown by device type, specifying fields, time increment, and date preset. ```APIDOC ## GET /stats ### Description Retrieves statistics for an entity with a breakdown by device type, specifying fields, time increment, and date preset. ### Method GET ### Endpoint /stats ### Parameters #### Query Parameters - **ids** (string) - Required - Comma-separated list of entity IDs. - **fields** (array of strings) - Required - List of fields to retrieve (e.g., ["clkCnt","ctr"]). - **timeIncrement** (string) - Required - Specifies the time granularity (e.g., "allDays"). - **breakdown** (string) - Required - Specifies the breakdown type, e.g., "pcMblTp" for device type. - **datePreset** (string) - Required - Specifies a predefined date range (e.g., "last7days"). ### Request Example { "example": "GET /stats?ids=camp_789&fields=[\"clkCnt\",\"ctr\"]&timeIncrement=allDays&breakdown=pcMblTp&datePreset=last7days" } ``` -------------------------------- ### Get single entity daily stats Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/stats.md Retrieves daily statistics for a single entity, specifying the fields, time increment, and date preset. ```APIDOC ## GET /stats ### Description Retrieves daily statistics for a single entity, specifying the fields, time increment, and date preset. ### Method GET ### Endpoint /stats ### Parameters #### Query Parameters - **id** (string) - Required - The ID of the entity. - **fields** (array of strings) - Required - List of fields to retrieve (e.g., ["clkCnt","impCnt"]). - **timeIncrement** (string) - Required - Specifies the time granularity, set to "1" for daily breakdown. - **datePreset** (string) - Required - Specifies a predefined date range (e.g., "last7days"). ### Request Example { "example": "GET /stats?id=adgroup_123&fields=[\"clkCnt\",\"impCnt\"]&timeIncrement=1&datePreset=last7days" } ``` -------------------------------- ### Load API Credentials from Environment Variables Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/configuration.md Load your Naver Search AD API credentials from environment variables into Python variables. Ensure the customer ID is converted to an integer. ```python import os API_KEY = os.getenv('SEARCHAD_API_KEY') SECRET_KEY = os.getenv('SEARCHAD_SECRET_KEY') CUSTOMER_ID = int(os.getenv('SEARCHAD_CUSTOMER_ID')) ``` -------------------------------- ### Configure Session with Keep-Alive and Retries Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/configuration.md Set up a requests Session with HTTP adapters to enable connection pooling (Keep-Alive) and configure retry strategies for specific HTTP status codes. ```python from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry session = requests.Session() retry_strategy = Retry( total=3, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504], method_whitelist=["HEAD", "GET", "OPTIONS"] ) adapter = HTTPAdapter(max_retries=retry_strategy) session.mount("http://", adapter) session.mount("https://", adapter) response = session.get(url, headers=headers) ``` -------------------------------- ### Retrieve Ad Group Targets Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/endpoints.md GET endpoint to retrieve targeting strategies for a specific ad group. The response is an object indexed by target type. ```http GET /ncc/adgroups/{nccAdgroupId}/targets ``` -------------------------------- ### Create Campaign Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/00-START-HERE.md Creates a new campaign within the account. ```APIDOC ## POST /ncc/campaigns ### Description Creates a new campaign. ### Method POST ### Endpoint /ncc/campaigns ``` -------------------------------- ### Estimate Performance for a Single Keyword Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/estimate.md Use this endpoint to estimate performance metrics (clicks, impressions, cost) for a single keyword across different bid amounts. Requires specifying device, keyword, and a list of bids. ```python uri = '/estimate/performance/keyword' method = 'POST' payload = { 'device': 'PC', 'keywordplus': True, 'key': '중고차', 'bids': [100, 500, 1000, 1500, 2000, 3000, 5000] } response = requests.post( BASE_URL + uri, json=payload, headers=get_header(method, uri) ) estimates = response.json() for perf in estimates.get('data', []): print(f"Bid: {perf['bid']}, Clicks: {perf['clicks']}, Cost: {perf['cost']}") ``` -------------------------------- ### Get stats with custom date range Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/stats.md Retrieves statistics for an entity using a custom date range, specifying fields, time increment, and the date range. ```APIDOC ## GET /stats ### Description Retrieves statistics for an entity using a custom date range, specifying fields, time increment, and the date range. ### Method GET ### Endpoint /stats ### Parameters #### Query Parameters - **id** (string) - Required - The ID of the entity. - **fields** (array of strings) - Required - List of fields to retrieve (e.g., ["clkCnt","cpc"]). - **timeIncrement** (string) - Required - Specifies the time granularity (e.g., "allDays"). - **timeRange** (object) - Required - Object defining the custom date range with 'since' and 'until' properties. - **since** (string) - Required - Start date in 'YYYY-MM-DD' format. - **until** (string) - Required - End date in 'YYYY-MM-DD' format. ### Request Example { "example": "GET /stats?id=keyword_456&fields=[\"clkCnt\",\"cpc\"]&timeIncrement=allDays&timeRange={\"since\":\"2024-01-01\",\"until\":\"2024-06-30\"}" } ``` -------------------------------- ### Create Channel Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/channels.md Creates a new business channel. Requires customer ID, API key, timestamp, and signature in headers. The request body must include channel details like name, type, customer ID, and business-specific information. ```Python uri = '/ncc/channels' method = 'POST' payload = { 'name': 'My Website', 'channelTp': 'SITE', 'customerId': CUSTOMER_ID, 'businessInfo': { 'site': 'https://example.com' } } response = requests.post( BASE_URL + uri, json=payload, headers=get_header(method, uri) ) new_channel = response.json() print(f"Created channel with ID: {new_channel['nccChannelId']}") ``` -------------------------------- ### API Reference Overview Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/README.md This section provides an overview of the available API resources for managing Naver Search AD campaigns, ad groups, keywords, ads, business channels, ad extensions, customer links, and estimation/statistics tools. ```APIDOC ## API Reference This section provides documentation for each API resource: - **Campaign Management**: CRUD operations, budget control. - **Ad Group Management**: Creation, targeting, and configuration. - **Keyword Management**: Bidding, quality index, and status. - **Advertisement Creative Management**: All ad types. - **Business Channel Management**: Website/property organization. - **Ad Extensions**: Callouts, sitelinks, location, etc. - **Account Relationship Management**: Managing customer links. - **Bid and Performance Estimation**: Tools for estimating bids and performance. - **Performance Statistics and Reporting**: Accessing campaign statistics and reports. ``` -------------------------------- ### Get Daily Statistics Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/stats.md Retrieves daily performance statistics for a single entity over a preset date range. Requires 'id', 'fields', and 'timeIncrement' set to '1'. ```python uri = '/stats' method = 'GET' fields = json.dumps(['clkCnt', 'impCnt', 'avgRnk']) response = requests.get( BASE_URL + uri, params={ 'id': entity_id, 'fields': fields, 'timeIncrement': '1', 'datePreset': 'last7days' }, headers=get_header(method, uri) ) daily_stats = response.json() if 'summary' in daily_stats: summary = daily_stats['summary'] print(f"Period: {summary['dateStart']} to {summary['dateEnd']}") for daily_data in daily_stats.get('data', []): print(f"Date: {daily_data['dateStart']}") print(f"Impressions: {daily_data['impCnt']}") print(f"Clicks: {daily_data['clkCnt']}") ``` -------------------------------- ### Create Channel Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/channels.md Creates a new business channel. Requires customer ID, API key, timestamp, and signature in the headers, along with channel details in the request body. ```APIDOC ## POST /ncc/channels ### Description Creates a new business channel. ### Method POST ### Endpoint /ncc/channels ### Parameters #### Header Parameters - **X-Customer** (long) - Required - Customer ID - **X-API-KEY** (string) - Required - API key - **X-Timestamp** (string) - Required - Current timestamp - **X-Signature** (string) - Required - HMAC-SHA256 signature ### Request Body - **name** (string) - Required - Channel name - **channelTp** (string) - Required - Channel type (e.g., "SITE") - **customerId** (long) - Required - Customer ID - **businessInfo** (object) - Required - Business information specific to channel type - **site** (string) - Required - Website URL for the channel (if channelTp is "SITE") ### Request Example ```json { "name": "My Website", "channelTp": "SITE", "customerId": 12345, "businessInfo": { "site": "https://example.com" } } ``` ### Response #### Success Response (200) Returns the created Channel object with assigned ID. ### Response Example ```json { "nccChannelId": "string", "customerId": 0, "name": "string", "channelTp": "string", "businessInfo": {} } ``` ``` -------------------------------- ### Get Specific Ad by ID Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/ads.md Retrieves a specific ad using its unique ID. The ad ID is part of the URL path, and authentication headers are required. ```Python uri = '/ncc/ads/' + ad_id method = 'GET' response = requests.get( BASE_URL + uri, headers=get_header(method, uri) ) ad = response.json() print(f"Ad content: {ad['ad']}") ``` -------------------------------- ### Project File Structure Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/INDEX.md This snippet displays the directory structure for the Naver Search AD API project. It outlines the location of key documentation files and API reference modules. ```text / ├── README.md # Start here ├── INDEX.md # This file ├── MANIFEST.txt # Content summary ├── types.md # Type definitions ├── endpoints.md # HTTP endpoints ├── errors.md # Error codes ├── configuration.md # Setup guide └── api-reference/ ├── campaigns.md # Campaign resource ├── adgroups.md # Ad group resource ├── keywords.md # Keyword resource ├── ads.md # Ad creative resource ├── channels.md # Channel resource ├── ad-extensions.md # Ad extension resource ├── customer-links.md # Account links ├── estimate.md # Estimation endpoints └── stats.md # Statistics endpoint ``` -------------------------------- ### Make API Calls for a Specific Client (Python) Source: https://github.com/naver/searchad-apidoc/blob/master/_autodocs/api-reference/customer-links.md After retrieving a client ID, use it in the 'X-Customer' header to make API calls on behalf of that specific client account. ```python # Use the client_id from above in X-Customer header uri = '/ncc/campaigns' method = 'GET' response = requests.get( BASE_URL + uri, headers=get_header(method, uri, api_key, secret_key, client_id) ) campaigns = response.json() ```