> ## Documentation Index
> Fetch the complete documentation index at: https://docs.benzinga.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 인증

> Benzinga API에 대한 요청을 인증하는 방법

Benzinga API는 요청을 인증하기 위해 **API 키**를 사용합니다. API 키는 구독에 따라 특정 데이터와 기능에 대한 액세스 권한을 부여하는 고유 식별자입니다.

<Note>
  **API 키를 안전하게 보관하세요.** GitHub, 클라이언트 측 코드, 암호화되지 않은 통신 등 공개적으로 접근 가능한 곳에 공유하지 마십시오. 키가 유출되었다고 생각되면 즉시 지원팀에 문의하세요.
</Note>

[Benzinga Developer Console](https://www.benzinga.com/apis/licensing/register)에서 API 키를 조회하고 관리할 수 있습니다.

<div id="authentication-methods">
  ## 인증 방법
</div>

Benzinga API는 두 가지 인증 방법을 지원합니다. 프로덕션 환경 애플리케이션에서는 보안성이 더 높고 URL 로그에 키가 노출되는 것을 방지할 수 있으므로 **HTTP 헤더** 방식을 사용할 것을 강력히 권장합니다.

<div id="1-http-header-recommended">
  ### 1. HTTP 헤더 (권장)
</div>

헤더로 인증하려면 `Authorization` 헤더에 `token <YOUR_API_KEY>` 값을 포함하세요.

```http theme={null}
Authorization: token <YOUR_API_KEY>
```

<div id="2-query-parameter">
  ### 2. Query Parameter
</div>

빠르게 테스트하거나 헤더를 수정할 수 없는 경우, `token`이라는 이름의 쿼리 파라미터로 키를 전달할 수 있습니다.

```http theme={null}
https://api.benzinga.com/api/v2/news?token=<YOUR_API_KEY>
```

<div id="code-examples">
  ## 코드 예시
</div>

다음은 여러 주요 언어에서 Benzinga API에 연결하기 위한, 프로덕션 환경에서 바로 사용할 수 있는 예시 코드입니다.

<CodeGroup>
  ```bash cURL theme={null}
  # 권장: 헤더 인증
  curl -L 'https://api.benzinga.com/api/v2/news?pageSize=1' \
  -H 'Authorization: token YOUR_API_KEY' \
  -H 'Accept: application/json'

  # 대안: 쿼리 매개변수
  curl -L 'https://api.benzinga.com/api/v2/news?pageSize=1&token=YOUR_API_KEY'
  ```

  ```python Python theme={null}
  import requests

  url = "https://api.benzinga.com/api/v2/news"

  # 권장: 헤더 인증
  headers = {
      "Authorization": "token YOUR_API_KEY",
      "Accept": "application/json"
  }

  params = {
      "pageSize": 1
  }

  try:
      response = requests.get(url, headers=headers, params=params)
      response.raise_for_status() # 4xx/5xx 응답에 대해 자세한 오류를 발생시킵니다
      data = response.json()
      print(data)
  except requests.exceptions.RequestException as e:
      print(f"데이터 가져오기 오류: {e}")
  ```

  ```javascript Node.js theme={null}
  const axios = require('axios');

  const url = 'https://api.benzinga.com/api/v2/news';
  const apiKey = 'YOUR_API_KEY';

  async function getNews() {
    try {
      const response = await axios.get(url, {
        headers: {
          'Authorization': `token ${apiKey}`,
          'Accept': 'application/json'
        },
        params: {
          pageSize: 1
        }
      });
      
      console.log(response.data);
    } catch (error) {
      if (error.response) {
        // 요청이 전송되었고 서버가 2xx 범위를 벗어나는 상태 코드로 응답한 경우
        console.error('오류 상태:', error.response.status);
        console.error('오류 데이터:', error.response.data);
      } else {
        console.error('오류 메시지:', error.message);
      }
    }
  }

  getNews();
  ```

  ```go Go theme={null}
  package main

  import (
  	"fmt"
  	"io/ioutil"
  	"net/http"
  )

  func main() {
  	url := "https://api.benzinga.com/api/v2/news?pageSize=1"
  	apiKey := "YOUR_API_KEY"

  	req, err := http.NewRequest("GET", url, nil)
  	if err != nil {
  		panic(err)
  	}

  	// 권장: 헤더 인증
  	req.Header.Add("Authorization", fmt.Sprintf("token %s", apiKey))
  	req.Header.Add("Accept", "application/json")

  	client := &http.Client{}
  	resp, err := client.Do(req)
  	if err != nil {
  		panic(err)
  	}
  	defer resp.Body.Close()

  	if resp.StatusCode >= 400 {
  		fmt.Printf("오류: 상태 코드 %d\n", resp.StatusCode)
  		return
  	}

  	body, err := ioutil.ReadAll(resp.Body)
  	if err != nil {
  		panic(err)
  	}

  	fmt.Println(string(body))
  }
  ```
</CodeGroup>

<div id="troubleshooting">
  ## 문제 해결
</div>

일반적인 인증 오류와 해결 방법입니다.

| Status Code | Message        | Possible Cause | Resolution                                                                                     |
| :---------- | :------------- | :------------- | :--------------------------------------------------------------------------------------------- |
| **401**     | `Unauthorized` | 잘못된 API 키      | API 키가 올바른지, 다시 생성되지 않았는지 확인하십시오. 불필요한 공백이 함께 복사되지 않았는지도 확인하십시오.                               |
| **401**     | `Unauthorized` | API 키 누락       | `Authorization` 헤더가 `token &lt;KEY&gt;` 형식으로 올바르게 설정되어 있거나 `token` 파라미터가 포함되어 있는지 확인하십시오.      |
| **403**     | `Forbidden`    | 권한 부족          | API 키는 유효하지만, 현재 요금제에는 요청한 endpoint에 대한 접근 권한이 포함되어 있지 않습니다. 요금제를 업그레이드하려면 영업팀 또는 지원팀에 문의하십시오. |
