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

# Gemini 네이티브 형식

>  - Google 네이티브 API 형식으로 Gemini 모델 호출
- 동기 처리 모드로 실시간 응답
- 최소한의 매개변수로 빠르게 시작 

<RequestExample>
  ```bash cURL theme={null}
  curl --request POST \
    --url https://api.apimart.ai/v1beta/models/gemini-2.5-pro:generateContent \
    --header 'Authorization: Bearer <token>' \
    --header 'Content-Type: application/json' \
    --data '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "안녕하세요, 자기소개를 해주세요"
          }
        ]
      }
    ]
  }'
  ```

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

  url = "https://api.apimart.ai/v1beta/models/gemini-2.5-pro:generateContent"

  payload = {
      "contents": [
          {
              "role": "user",
              "parts": [
                  {
                      "text": "안녕하세요, 자기소개를 해주세요"
                  }
              ]
          }
      ]
  }

  headers = {
      "Authorization": "Bearer <token>",
      "Content-Type": "application/json"
  }

  response = requests.post(url, json=payload, headers=headers)

  print(response.json())
  ```

  ```javascript JavaScript theme={null}
  const url = "https://api.apimart.ai/v1beta/models/gemini-2.5-pro:generateContent";

  const payload = {
    contents: [
      {
        role: "user",
        parts: [
          {
            text: "안녕하세요, 자기소개를 해주세요"
          }
        ]
      }
    ]
  };

  const headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
  };

  fetch(url, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(payload)
  })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
  ```

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

  import (
      "bytes"
      "encoding/json"
      "fmt"
      "io/ioutil"
      "net/http"
  )

  func main() {
      url := "https://api.apimart.ai/v1beta/models/gemini-2.5-pro:generateContent"

      payload := map[string]interface{}{
          "contents": []map[string]interface{}{
              {
                  "role": "user",
                  "parts": []map[string]interface{}{
                      {
                          "text": "안녕하세요, 자기소개를 해주세요",
                      },
                  },
              },
          },
      }

      jsonData, _ := json.Marshal(payload)

      req, _ := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
      req.Header.Set("Authorization", "Bearer <token>")
      req.Header.Set("Content-Type", "application/json")

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

      body, _ := ioutil.ReadAll(resp.Body)
      fmt.Println(string(body))
  }
  ```

  ```java Java theme={null}
  import java.net.http.HttpClient;
  import java.net.http.HttpRequest;
  import java.net.http.HttpResponse;
  import java.net.URI;

  public class Main {
      public static void main(String[] args) throws Exception {
          String url = "https://api.apimart.ai/v1beta/models/gemini-2.5-pro:generateContent";

          String payload = """
          {
            "contents": [
              {
                "role": "user",
                "parts": [
                  {
                    "text": "안녕하세요, 자기소개를 해주세요"
                  }
                ]
              }
            ]
          }
          """;

          HttpClient client = HttpClient.newHttpClient();
          HttpRequest request = HttpRequest.newBuilder()
              .uri(URI.create(url))
              .header("Authorization", "Bearer <token>")
              .header("Content-Type", "application/json")
              .POST(HttpRequest.BodyPublishers.ofString(payload))
              .build();

          HttpResponse<String> response = client.send(request,
              HttpResponse.BodyHandlers.ofString());

          System.out.println(response.body());
      }
  }
  ```

  ```php PHP theme={null}
  <?php

  $url = "https://api.apimart.ai/v1beta/models/gemini-2.5-pro:generateContent";

  $payload = [
      "contents" => [
          [
              "role" => "user",
              "parts" => [
                  [
                      "text" => "안녕하세요, 자기소개를 해주세요"
                  ]
              ]
          ]
      ]
  ];

  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
      "Authorization: Bearer <token>",
      "Content-Type: application/json"
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  echo $response;
  ?>
  ```

  ```ruby Ruby theme={null}
  require 'net/http'
  require 'json'
  require 'uri'

  url = URI("https://api.apimart.ai/v1beta/models/gemini-2.5-pro:generateContent")

  payload = {
    contents: [
      {
        role: "user",
        parts: [
          {
            text: "안녕하세요, 자기소개를 해주세요"
          }
        ]
      }
    ]
  }

  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = true

  request = Net::HTTP::Post.new(url)
  request["Authorization"] = "Bearer <token>"
  request["Content-Type"] = "application/json"
  request.body = payload.to_json

  response = http.request(request)
  puts response.body
  ```
</RequestExample>

<ResponseExample>
  ```json 200 theme={null}
  {
    "code": 200,
    "data": {
      "candidates": [
        {
          "content": {
            "role": "model",
            "parts": [
              {
                "text": "안녕하세요! 제 소개를 드리겠습니다.\n\n저는 Google에서 훈련하고 개발한 대규모 언어 모델입니다..."
              }
            ]
          },
          "finishReason": "STOP",
          "index": 0,
          "safetyRatings": [
            {
              "category": "HARM_CATEGORY_HATE_SPEECH",
              "probability": "NEGLIGIBLE"
            }
          ]
        }
      ],
      "promptFeedback": {
        "safetyRatings": [
          {
            "category": "HARM_CATEGORY_HATE_SPEECH",
            "probability": "NEGLIGIBLE"
          }
        ]
      ]
    },
    "usageMetadata": {
      "promptTokenCount": 4,
      "candidatesTokenCount": 611,
      "totalTokenCount": 2422,
      "thoughtsTokenCount": 1807,
      "promptTokensDetails": [
        {
          "modality": "TEXT",
          "tokenCount": 4
        }
      ]
    }
  }
  ```

  ```json 400 theme={null}
  {
    "error": {
      "code": 400,
      "message": "유효하지 않은 요청 매개변수입니다",
      "status": "INVALID_ARGUMENT"
    }
  }
  ```

  ```json 401 theme={null}
  {
    "error": {
      "code": 401,
      "message": "인증에 실패했습니다. API 키를 확인하세요",
      "status": "UNAUTHENTICATED"
    }
  }
  ```

  ```json 402 theme={null}
  {
    "error": {
      "code": 402,
      "message": "잔액이 부족합니다. 충전해주세요",
      "status": "PAYMENT_REQUIRED"
    }
  }
  ```

  ```json 403 theme={null}
  {
    "error": {
      "code": 403,
      "message": "접근이 거부되었습니다",
      "status": "PERMISSION_DENIED"
    }
  }
  ```

  ```json 404 theme={null}
  {
    "error": {
      "code": 404,
      "message": "지정된 모델을 찾을 수 없습니다",
      "status": "NOT_FOUND"
    }
  }
  ```

  ```json 429 theme={null}
  {
    "error": {
      "code": 429,
      "message": "요청이 너무 빈번합니다. 나중에 다시 시도하세요",
      "status": "RESOURCE_EXHAUSTED"
    }
  }
  ```

  ```json 500 theme={null}
  {
    "error": {
      "code": 500,
      "message": "서버 내부 오류",
      "status": "INTERNAL"
    }
  }
  ```

  ```json 502 theme={null}
  {
    "error": {
      "code": 502,
      "message": "게이트웨이 오류, 서비스를 일시적으로 사용할 수 없습니다",
      "status": "BAD_GATEWAY"
    }
  }
  ```

  ```json 503 theme={null}
  {
    "error": {
      "code": 503,
      "message": "서비스를 일시적으로 사용할 수 없습니다",
      "status": "UNAVAILABLE"
    }
  }
  ```
</ResponseExample>

## 인증

<ParamField header="Authorization" type="string" required>
  모든 API 엔드포인트에는 Bearer Token 인증이 필요합니다

  API 키 가져오기:

  [API 키 관리 페이지](https://apimart.ai/keys)를 방문하여 API 키를 가져오세요

  요청 헤더에 추가:

  ```
  Authorization: Bearer YOUR_API_KEY
  ```
</ParamField>

## 경로 매개변수

<ParamField path="model" type="string" required>
  모델 이름

  예제에서는 `gemini-2.5-pro`를 사용하며, 다른 지원되는 Gemini 모델로 대체할 수 있습니다:

  * `gemini-3.5-flash` - Gemini 3.5 고속 버전
  * `gemini-3.1-pro-preview` - Gemini 3.1 Pro 미리보기 버전
  * `gemini-3-pro-preview` - Gemini 3 Pro 미리보기 버전
  * `gemini-2.5-pro` - Gemini 2.5 전문 버전
</ParamField>

<ParamField path="method" type="enum<string>" required>
  생성 방법 (빠른 시작에는 `generateContent` 권장):

  * `generateContent`: 완전한 응답을 기다린 후 한 번에 반환
  * `streamGenerateContent`: 스트림 형식으로 단계적으로 콘텐츠 반환

  사용 가능한 옵션: `generateContent`, `streamGenerateContent`
</ParamField>

## 본문

<ParamField body="contents" type="array" required>
  대화 내용 목록

  최소 1개의 메시지가 필요합니다

  <Expandable title="contents 객체 구조">
    <ParamField body="role" type="string" required>
      역할 유형:

      * `user`: 사용자 메시지
      * `model`: 모델 응답 (대화 기록에서 사용)
    </ParamField>

    <ParamField body="parts" type="array" required>
      메시지 내용 부분

      <Expandable title="parts 객체 구조">
        <ParamField body="text" type="string">
          텍스트 내용
        </ParamField>

        <ParamField body="inlineData" type="object">
          인라인 데이터 (멀티모달 입력용)

          <Expandable title="inlineData 속성">
            <ParamField body="mimeType" type="string">
              MIME 타입, 예: `image/jpeg`, `image/png`
            </ParamField>

            <ParamField body="data" type="string">
              Base64 인코딩된 데이터
            </ParamField>
          </Expandable>
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>

  예:

  ```json theme={null}
  [
    {
      "role": "user",
      "parts": [{ "text": "안녕하세요, 자기소개를 해주세요" }]
    }
  ]
  ```
</ParamField>

<ParamField body="generationConfig" type="object">
  생성 구성 (선택사항)

  <Expandable title="generationConfig 속성">
    <ParamField body="temperature" type="number">
      출력 무작위성 제어, 범위 0.0-2.0

      * 낮은 값은 출력을 더 결정적으로 만듭니다
      * 높은 값은 출력을 더 무작위로 만듭니다

      기본값: 1.0
    </ParamField>

    <ParamField body="maxOutputTokens" type="integer">
      생성할 최대 토큰 수

      모델마다 최대 제한이 다릅니다
    </ParamField>

    <ParamField body="topP" type="number">
      핵 샘플링 매개변수, 범위 0.0-1.0

      샘플링 시 고려되는 확률 질량 제어
    </ParamField>

    <ParamField body="topK" type="integer">
      Top-K 샘플링 매개변수

      각 단계에서 가장 확률이 높은 K개의 토큰에서만 샘플링
    </ParamField>

    <ParamField body="stopSequences" type="array">
      중지 시퀀스 목록

      이러한 시퀀스를 만나면 생성 중지
    </ParamField>
  </Expandable>
</ParamField>

<ParamField body="safetySettings" type="array">
  안전 설정 (선택사항)

  <Expandable title="safetySettings 객체 구조">
    <ParamField body="category" type="string">
      안전 카테고리:

      * `HARM_CATEGORY_HATE_SPEECH`: 혐오 발언
      * `HARM_CATEGORY_DANGEROUS_CONTENT`: 위험한 콘텐츠
      * `HARM_CATEGORY_HARASSMENT`: 괴롭힘
      * `HARM_CATEGORY_SEXUALLY_EXPLICIT`: 성적으로 노골적인 콘텐츠
    </ParamField>

    <ParamField body="threshold" type="string">
      임계값 수준:

      * `BLOCK_NONE`: 차단하지 않음
      * `BLOCK_ONLY_HIGH`: 높은 위험만 차단
      * `BLOCK_MEDIUM_AND_ABOVE`: 중간 이상 위험 차단
      * `BLOCK_LOW_AND_ABOVE`: 낮은 이상 위험 차단
    </ParamField>
  </Expandable>
</ParamField>

## 응답

<ResponseField name="candidates" type="array">
  후보 응답 목록

  <Expandable title="candidates 객체 구조">
    <ResponseField name="content" type="object">
      생성된 콘텐츠

      <Expandable title="content 속성">
        <ResponseField name="role" type="string">
          역할, 일반적으로 `model`
        </ResponseField>

        <ResponseField name="parts" type="array">
          콘텐츠 부분 목록

          <Expandable title="parts 객체">
            <ResponseField name="text" type="string">
              생성된 텍스트 콘텐츠
            </ResponseField>
          </Expandable>
        </ResponseField>
      </Expandable>
    </ResponseField>

    <ResponseField name="finishReason" type="string">
      완료 이유:

      * `STOP`: 정상 완료
      * `MAX_TOKENS`: 최대 토큰 제한 도달
      * `SAFETY`: 안전상의 이유로 중지
      * `RECITATION`: 반복으로 인해 중지
      * `OTHER`: 기타 이유
    </ResponseField>

    <ResponseField name="index" type="integer">
      후보 응답의 인덱스
    </ResponseField>

    <ResponseField name="safetyRatings" type="array">
      안전 등급 목록

      <Expandable title="safetyRatings 객체">
        <ResponseField name="category" type="string">
          안전 카테고리
        </ResponseField>

        <ResponseField name="probability" type="string">
          확률 수준: `NEGLIGIBLE`, `LOW`, `MEDIUM`, `HIGH`
        </ResponseField>
      </Expandable>
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="promptFeedback" type="object">
  프롬프트 피드백 정보

  <Expandable title="promptFeedback 속성">
    <ResponseField name="safetyRatings" type="array">
      프롬프트의 안전 등급
    </ResponseField>

    <ResponseField name="blockReason" type="string">
      차단 이유 (프롬프트가 차단된 경우)
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="usageMetadata" type="object">
  사용량 통계

  <Expandable title="usageMetadata 속성">
    <ResponseField name="promptTokenCount" type="integer">
      프롬프트의 토큰 수
    </ResponseField>

    <ResponseField name="candidatesTokenCount" type="integer">
      후보 응답의 토큰 수
    </ResponseField>

    <ResponseField name="totalTokenCount" type="integer">
      소비된 총 토큰 수
    </ResponseField>

    <ResponseField name="thoughtsTokenCount" type="integer">
      사고에 사용된 토큰 수 (해당되는 경우)
    </ResponseField>

    <ResponseField name="promptTokensDetails" type="array">
      프롬프트 토큰 세부정보

      <Expandable title="promptTokensDetails 객체">
        <ResponseField name="modality" type="string">
          모달리티 유형: `TEXT`, `IMAGE`, 등
        </ResponseField>

        <ResponseField name="tokenCount" type="integer">
          이 모달리티의 토큰 수
        </ResponseField>
      </Expandable>
    </ResponseField>
  </Expandable>
</ResponseField>
