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

# Create Query Token

> Issues a query token for [Run Query](/en/api-reference/queries/run-query) and returns the request body to send with it. See [Query the Knowledge Base](/en/api-reference/guides/knowledge-base#query-the-knowledge-base) for details.



## OpenAPI

````yaml /en/api-reference/openapi_service.json post /knowledge-fs/spaces/{knowledge_base_id}/queries/admission
openapi: 3.0.1
info:
  description: >-
    REST API for Dify applications and knowledge bases. Application endpoints
    authenticate with an app API key; knowledge endpoints authenticate with a
    dataset API key.
  title: Dify Service API
  version: 1.0.0
servers:
  - description: >-
      Base URL of the Dify Service API. For self-hosted deployments, replace it
      with your own API base URL.
    url: https://{api_base_url}
    variables:
      api_base_url:
        default: api.dify.ai/v1
        description: Host and path of the API base URL, without the `https://` prefix.
security:
  - ApiKeyAuth: []
tags:
  - description: Operations related to chat messages and interactions.
    name: Chat Messages
  - description: File upload and preview operations.
    name: Files
  - description: Operations related to end user information.
    name: End Users
  - description: User feedback operations.
    name: Feedback
  - description: Operations related to managing conversations.
    name: Conversations
  - description: Text-to-Speech and Speech-to-Text operations.
    name: Audio
  - description: Operations to retrieve application settings and information.
    name: Applications
  - description: Operations related to managing annotations for direct replies.
    name: Annotations
  - description: Endpoints for resuming paused workflows that require human input.
    name: Human Input
  - description: Operations for executing and managing workflows.
    name: Workflow Runs
  - description: Operations related to text generation and completion.
    name: Completion Messages
  - description: >-
      Operations for managing knowledge bases, including creation,
      configuration, and retrieval.
    name: Knowledge Bases
  - description: >-
      Operations for creating, updating, and managing documents within a
      knowledge base.
    name: Documents
  - description: Operations for managing document chunks and child chunks.
    name: Chunks
  - description: >-
      Operations for managing knowledge base metadata fields and document
      metadata values.
    name: Metadata
  - description: Operations for managing knowledge base tags and tag bindings.
    name: Tags
  - description: Operations for retrieving available models.
    name: Models
  - description: >-
      Operations for managing and running knowledge pipelines, including
      datasource plugins and pipeline execution.
    name: Knowledge Pipeline
  - description: Ask a knowledge base a question and stream the answer.
    name: Queries
  - description: Inspect what a query retrieved and why.
    name: Query Records
  - description: Run a research question in the background and collect its results.
    name: Research Tasks
  - description: >-
      Read the documents in a knowledge base, their files, revisions, and
      chunks; label documents with metadata.
    name: Documents and Chunks
  - description: >-
      Follow, cancel, or retry indexing, and list the knowledge base's
      background tasks.
    name: Indexing Tasks
  - description: >-
      Follow the deletion of a document file, a batch of files, or a source
      until it finishes.
    name: Deletion Jobs
  - description: >-
      Manage the sources that feed a knowledge base, their sync schedules, and
      their connections.
    name: Sources
  - description: >-
      Sync a source now, import website pages or provider items, and follow,
      cancel, or retry the runs.
    name: Source Syncs and Imports
  - description: >-
      Read and change the knowledge base's models and retrieval settings, and
      follow the migration a change starts.
    name: Settings
paths:
  /knowledge-fs/spaces/{knowledge_base_id}/queries/admission:
    post:
      tags:
        - Queries
      summary: Create Query Token
      description: >-
        Issues a query token for [Run
        Query](/en/api-reference/queries/run-query) and returns the request body
        to send with it. See [Query the Knowledge
        Base](/en/api-reference/guides/knowledge-base#query-the-knowledge-base)
        for details.
      operationId: createQueryToken
      parameters:
        - description: >-
            Knowledge base ID: the last segment of the Service API endpoint
            shown in the knowledge base's **API Access** dialog
            (`…/knowledge-fs/spaces/<knowledge base ID>`), and the segment after
            `/datasets/new/` in the address bar.
          in: path
          name: knowledge_base_id
          required: true
          schema:
            format: uuid
            type: string
      requestBody:
        content:
          application/json:
            examples:
              request:
                summary: Request Example - New session
                value:
                  mode: fast
                  query: What changed in the refund policy this quarter?
              request_session:
                summary: Request Example - With a session ID
                value:
                  activeDocumentIds: []
                  activeEntityIds: []
                  mode: fast
                  query: What is the refund window for monthly plans?
                  sessionId: a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d
            schema:
              additionalProperties: false
              description: Provide a nonblank `query`.
              properties:
                activeDocumentIds:
                  description: >-
                    These IDs do not filter or rank retrieved content. Leave
                    empty.
                  items:
                    type: string
                  maxItems: 100
                  type: array
                activeEntityIds:
                  description: >-
                    These IDs do not filter or rank retrieved content. Leave
                    empty.
                  items:
                    type: string
                  maxItems: 100
                  type: array
                mode:
                  description: >-
                    Retrieval depth: `fast`, `deep`, or `research` (see
                    [Retrieval
                    Depth](/en/cloud/use-dify/knowledge-base/retrieval-settings#retrieval-depth)).
                    Omit it (or send `null`) to use the knowledge base's default
                    depth, `retrieval.default_mode` in [Get Knowledge Base
                    Settings](/en/api-reference/settings/get-knowledge-base-settings).
                  enum:
                    - fast
                    - deep
                    - research
                    - null
                  nullable: true
                  type: string
                query:
                  description: >-
                    The question. Use a nonblank query. Also limited to 16,384
                    UTF-8 bytes.
                  maxLength: 16000
                  nullable: false
                  pattern: \S
                  type: string
                sessionId:
                  description: >-
                    ID of a query session, as a UUID. Omit it to start a new
                    session. [Run Query](/en/api-reference/queries/run-query)
                    returns the session ID in its `x-session-id` response
                    header.


                    A session stores the last 20 queries but doesn't carry them
                    into later answers. It expires after 30 minutes without a
                    query.


                    An expired or unknown ID starts a fresh session under that
                    ID, so a UUID you generate yourself stays valid as that
                    session's ID.
                  nullable: true
                  type: string
              required:
                - query
              type: object
        description: |-
          Unknown fields answer `400`.

          Optional fields marked nullable treat `null` as omitted.
        required: true
      responses:
        '200':
          content:
            application/json:
              examples:
                success:
                  summary: Response Example - New session
                  value:
                    expires_at: '2026-09-06T08:31:07Z'
                    operation_id: createQuery
                    request:
                      activeDocumentIds: []
                      activeEntityIds: []
                      knowledgeSpaceId: 8d2c6a1e-5b3f-4c7d-9e01-2a3b4c5d6e7f
                      mode: fast
                      query: What changed in the refund policy this quarter?
                    token: >-
                      eyJhbGciOiJSUzI1NiIsImtpZCI6Imtmcy0yMDI2LTA5In0.eyJpc3MiOiJkaWZ5LWNvbnRyb2wtcGxhbmUiLCJhdWQiOiJrbm93bGVkZ2UtZnMiLCJzdWIiOiJkaWZ5LWRhdGFzZXQtYXBpLWtleTo3YjRjOWUyMS0zZDVmLTRhNmItOGM3ZC05ZTBmMWEyYjNjNGQiLCJhY3Rpb24iOiJxdWVyaWVzLmNyZWF0ZSIsInRyYWNlX2lkIjoiM2YxZTlhN2MtMmI0ZC00ZTZmLThhOTAtMWIyYzNkNGU1ZjYwIiwiZXhwIjoxNzg4NjgzNDY3fQ.V2s9Rm5xR2ZUZ0J2M2Q5aW1KU3hqUXJsV1pKcGtnQUFCZUtGMQ
                    trace_id: 3f1e9a7c-2b4d-4e6f-8a90-1b2c3d4e5f60
                    url: https://api.example.com/v1/knowledge-fs/query-stream
                success_session:
                  summary: Response Example - With a session ID
                  value:
                    expires_at: '2026-09-06T08:33:52Z'
                    operation_id: createQuery
                    request:
                      activeDocumentIds: []
                      activeEntityIds: []
                      knowledgeSpaceId: 8d2c6a1e-5b3f-4c7d-9e01-2a3b4c5d6e7f
                      mode: fast
                      query: What is the refund window for monthly plans?
                      sessionId: a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d
                    token: >-
                      eyJhbGciOiJSUzI1NiIsImtpZCI6Imtmcy0yMDI2LTA5In0.eyJpc3MiOiJkaWZ5LWNvbnRyb2wtcGxhbmUiLCJhdWQiOiJrbm93bGVkZ2UtZnMiLCJzdWIiOiJkaWZ5LWRhdGFzZXQtYXBpLWtleTo3YjRjOWUyMS0zZDVmLTRhNmItOGM3ZC05ZTBmMWEyYjNjNGQiLCJhY3Rpb24iOiJxdWVyaWVzLmNyZWF0ZSIsInRyYWNlX2lkIjoiN2Q0YTFjOGUtNWY2MC00YjIzLTlhN2QtOGUwZjFhMmIzYzRkIiwiZXhwIjoxNzg4NjgzNjMyfQ.TnBHc0xxUjBkWWJ4M2VBaW1KU3hqUXJsV1pKcGtnQUFCZUtGMg
                    trace_id: 7d4a1c8e-5f60-4b23-9a7d-8e0f1a2b3c4d
                    url: https://api.example.com/v1/knowledge-fs/query-stream
              schema:
                properties:
                  expires_at:
                    description: >-
                      When the token expires, as an ISO 8601 timestamp in UTC.
                      At most 60 seconds after issue. The deployment can shorten
                      the lifetime.
                    type: string
                  operation_id:
                    description: >-
                      Always `createQuery`, the operation the token is valid
                      for. Callers can ignore it.
                    type: string
                  request:
                    description: >-
                      Request body for [Run
                      Query](/en/api-reference/queries/run-query). Send it
                      unchanged.
                    properties:
                      activeDocumentIds:
                        description: The document IDs, as sent. `[]` when omitted.
                        items:
                          type: string
                        type: array
                      activeEntityIds:
                        description: The entity IDs, as sent. `[]` when omitted.
                        items:
                          type: string
                        type: array
                      knowledgeSpaceId:
                        description: >-
                          Internal ID of the knowledge base. Not the knowledge
                          base ID in the path. It is bound into the token, and
                          [Run Query](/en/api-reference/queries/run-query)
                          rejects a body whose `knowledgeSpaceId` does not match
                          the token.
                        type: string
                      mode:
                        description: The retrieval depth, as sent. `null` when omitted.
                        nullable: true
                        type: string
                      query:
                        description: >-
                          The question from your request. Can be `null` when the
                          request contains image references.
                        maxLength: 16000
                        nullable: true
                        pattern: \S
                        type: string
                      sessionId:
                        description: The session ID, as sent. Absent when omitted.
                        nullable: true
                        type: string
                    type: object
                  token:
                    description: >-
                      Query token for [Run
                      Query](/en/api-reference/queries/run-query) on this
                      knowledge base, good until `expires_at`. Send it as
                      `Authorization: Bearer <token>`. 


                      Create a new token for each call, including a retry.


                      It is a signed JWT. Read `trace_id` from this response for
                      the `X-Trace-ID` header; you do not need to decode the
                      token.
                    type: string
                  trace_id:
                    description: >-
                      Value to send as the `X-Trace-ID` header of [Run
                      Query](/en/api-reference/queries/run-query). It equals the
                      token's `trace_id` claim. It is not the query record ID.
                    type: string
                  url:
                    description: >-
                      Where to send [Run
                      Query](/en/api-reference/queries/run-query). An absolute
                      URL when the deployment sets `SERVICE_API_URL`. Otherwise
                      the path `/v1/knowledge-fs/query-stream`, which already
                      carries the `/v1` prefix. Resolve that form against the
                      scheme and host of your endpoint, not against the
                      endpoint's path.
                    type: string
                type: object
          description: Query token issued.
        '400':
          content:
            application/json:
              examples:
                knowledge_fs_invalid_request:
                  summary: knowledge_fs_invalid_request
                  value:
                    code: knowledge_fs_invalid_request
                    message: Agent Knowledge Base request is invalid.
                    status: 400
                    violations:
                      - field:
                          - query
                        type: string_too_long
          description: >-
            - `knowledge_fs_invalid_request`: the request failed validation.
            `violations` names each failing field.
        '401':
          content:
            application/json:
              examples:
                knowledge_fs_invalid_credential:
                  summary: knowledge_fs_invalid_credential
                  value:
                    code: knowledge_fs_invalid_credential
                    message: Invalid Agent Knowledge Base service credential.
                    status: 401
                unauthorized_1:
                  summary: unauthorized (header missing)
                  value:
                    code: unauthorized
                    message: >-
                      Authorization header must be provided and start with
                      'Bearer'
                    status: 401
                unauthorized_2:
                  summary: unauthorized (key unknown)
                  value:
                    code: unauthorized
                    message: Access token is invalid
                    status: 401
          description: >-
            - `unauthorized`: the `Authorization` header is missing, or the key
            is unknown or not a knowledge base API key.

            - `knowledge_fs_invalid_credential`: the key is valid, but no
            knowledge base with this ID exists in the key's workspace, or the
            key is not tied to a workspace.
        '403':
          content:
            application/json:
              examples:
                forbidden:
                  summary: forbidden (rate limit)
                  value:
                    code: forbidden
                    message: >-
                      Sorry, you have reached the knowledge base request rate
                      limit of your subscription.
                    status: 403
                knowledge_fs_access_denied:
                  summary: knowledge_fs_access_denied
                  value:
                    code: knowledge_fs_access_denied
                    message: Agent Knowledge Base operation is not allowed.
                    status: 403
          description: >-
            - `knowledge_fs_access_denied`: the key is scoped to other knowledge
            bases, **API access** is off for this knowledge base, or the
            knowledge base is not active.

            - `knowledge_fs_access_denied`: the key's access to this knowledge
            base was revoked while the token was being issued.

            - `forbidden`: on Dify Cloud, the workspace has reached the
            knowledge base request rate limit of its subscription. Every call
            counts, reads included.
        '404':
          content:
            application/json:
              examples:
                not_found:
                  summary: not_found (feature off)
                  value:
                    code: not_found
                    message: >-
                      The requested URL was not found on the server. If you
                      entered the URL manually please check your spelling and
                      try again.
                    status: 404
          description: >-
            - `not_found`: the Agent Knowledge Base feature is turned off on
            this deployment.
        '503':
          content:
            application/json:
              examples:
                knowledge_fs_operation_unavailable:
                  summary: knowledge_fs_operation_unavailable
                  value:
                    code: knowledge_fs_operation_unavailable
                    message: Agent Knowledge Base operation is not available.
                    status: 503
          description: >-
            - `knowledge_fs_operation_unavailable`: the Agent Knowledge Base
            feature is not set up for this workspace, this operation is not
            available on the deployment, or the key's access to this knowledge
            base changed while the request was being authorized. Ask for a new
            token.

            - `knowledge_fs_operation_unavailable`: the knowledge base was
            upgraded from a classic knowledge base and is still disabling the
            documents that were disabled or archived there. Retry later.
components:
  securitySchemes:
    ApiKeyAuth:
      bearerFormat: API_KEY
      description: >-
        Every request authenticates with an API key: `Authorization: Bearer
        {API_KEY}`. App endpoints take an app API key; knowledge endpoints take
        a knowledge base API key ([Get
        Started](/en/api-reference/guides/get-started)).


        Keep keys server-side; never embed them in client code. Requests with a
        missing or invalid key fail with HTTP `401` (`unauthorized`).
      scheme: bearer
      type: http

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.