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

# Upsert

> Insert or update a taxonomy (schema/hierarchy) in the database.

## Request Body

| Field                  | Type             | Description                                                          |
|------------------------|------------------|----------------------------------------------------------------------|
| `taxonomy_name`        | `str`            | Name of the taxonomy to upsert.                                      |
| `new_taxonomy_name`    | `Optional[str]`  | New name for the taxonomy (when updating).                           |
| `taxonomy_description` | `Optional[str]`  | Description of the taxonomy.                                         |
| `taxonomy_data`        | `Optional[Dict]` | The taxonomy/hierarchy data structure.                               |

## Response

- **200**: Taxonomy upserted successfully  
    - Returns: `{ "taxonomy_name": str }`
- **500**: Internal Server Error

## Example

```json
{
  "taxonomy_name": "document-categories",
  "taxonomy_description": "Main document classification taxonomy",
  "taxonomy_data": {
    "invoice": ["purchase_invoice", "sales_invoice"],
    "receipt": ["expense_receipt", "payment_receipt"]
  }
}
```



## OpenAPI

````yaml /deasy-openapi-stainless.yml post /taxonomy/upsert
openapi: 3.1.0
info:
  title: FastAPI
  version: 0.1.0
servers:
  - url: /rest/unstructured
security: []
paths:
  /taxonomy/upsert:
    post:
      tags:
        - Taxonomies
      summary: Upsert
      description: >-
        Insert or update a taxonomy (schema/hierarchy) in the database.


        ## Request Body


        | Field                  | Type             |
        Description                                                          |

        |------------------------|------------------|----------------------------------------------------------------------|

        | `taxonomy_name`        | `str`            | Name of the taxonomy to
        upsert.                                      |

        | `new_taxonomy_name`    | `Optional[str]`  | New name for the taxonomy
        (when updating).                           |

        | `taxonomy_description` | `Optional[str]`  | Description of the
        taxonomy.                                         |

        | `taxonomy_data`        | `Optional[Dict]` | The taxonomy/hierarchy
        data structure.                               |


        ## Response


        - **200**: Taxonomy upserted successfully  
            - Returns: `{ "taxonomy_name": str }`
        - **500**: Internal Server Error


        ## Example


        ```json

        {
          "taxonomy_name": "document-categories",
          "taxonomy_description": "Main document classification taxonomy",
          "taxonomy_data": {
            "invoice": ["purchase_invoice", "sales_invoice"],
            "receipt": ["expense_receipt", "payment_receipt"]
          }
        }

        ```
      operationId: upsert_taxonomy_route_taxonomy_upsert_post
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UpsertTaxonomyRequest'
        required: true
      responses:
        '200':
          description: Successful Response
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/TaxonomyOperationResponse'
        '403':
          description: Missing token
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPError'
        '404':
          description: Resource not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPError'
        '422':
          description: Validation Error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPValidationError'
        '429':
          description: Too many requests
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPError'
        '500':
          description: >-
            Internal Server Error. An unexpected error occurred while processing
            the request.
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/HTTPError'
      security:
        - BasicAuth: []
        - BearerAuth: []
          UserIdAuth: []
      x-codeSamples:
        - lang: Python
          source: |-
            import os
            from unstructured import UnstructuredClient

            client = UnstructuredClient(
                username=os.environ.get("UNSTRUCTURED_USERNAME"),  # This is the default and can be omitted
                password=os.environ.get("UNSTRUCTURED_PASSWORD"),  # This is the default and can be omitted
            )
            taxonomy_operation_response = client.taxonomy.upsert(
                taxonomy_name="taxonomy_name",
            )
            print(taxonomy_operation_response.taxonomy_name)
        - lang: JavaScript
          source: >-
            import UnstructuredClient from 'unstructured-sdk';


            const client = new UnstructuredClient({
              authMethod: 'My Auth Method',
              username: process.env['UNSTRUCTURED_USERNAME'], // This is the default and can be omitted
              password: process.env['UNSTRUCTURED_PASSWORD'], // This is the default and can be omitted
            });


            const taxonomyOperationResponse = await client.taxonomy.upsert({
            taxonomy_name: 'taxonomy_name' });


            console.log(taxonomyOperationResponse.taxonomy_name);
components:
  schemas:
    UpsertTaxonomyRequest:
      properties:
        taxonomy_name:
          type: string
          title: Taxonomy Name
        new_taxonomy_name:
          anyOf:
            - type: string
            - type: 'null'
          title: New Taxonomy Name
        taxonomy_description:
          anyOf:
            - type: string
            - type: 'null'
          title: Taxonomy Description
        taxonomy_data:
          anyOf:
            - $ref: '#/components/schemas/TaxonomyGraph-Input'
            - type: object
            - type: 'null'
          title: Taxonomy Data
      type: object
      required:
        - taxonomy_name
      title: UpsertTaxonomyRequest
    TaxonomyOperationResponse:
      properties:
        taxonomy_name:
          type: string
          title: Taxonomy Name
      type: object
      required:
        - taxonomy_name
      title: TaxonomyOperationResponse
    HTTPError:
      properties:
        detail:
          type: string
          title: Detail
      type: object
      required:
        - detail
      title: HTTPError
    HTTPValidationError:
      properties:
        detail:
          items:
            $ref: '#/components/schemas/ValidationError'
          type: array
          title: Detail
      type: object
      title: HTTPValidationError
    TaxonomyGraph-Input:
      properties:
        nodes:
          items:
            $ref: '#/components/schemas/TaxonomyNode'
          type: array
          title: Nodes
        edges:
          items:
            $ref: '#/components/schemas/TaxonomyEdge'
          type: array
          title: Edges
        root_node_id:
          type: string
          title: Root Node Id
          description: ID of the root node
          default: root
      type: object
      title: TaxonomyGraph
      description: |-
        A node/edge style graph representation of a taxonomy.

        Example (simple case - single condition per edge):
            graph = TaxonomyGraph(
                nodes=[
                    TaxonomyNode(node_id="1", name="Document Type", active_values=["Contract", "Invoice"]),
                    TaxonomyNode(node_id="2", name="Contract Type", active_values=["NDA", "Employment"]),
                ],
                edges=[
                    TaxonomyEdge(
                        target_node_ids=["1"],
                        conditions=[EdgeCondition(node_id="root", tag_value_name="Contract")],
                    ),
                    TaxonomyEdge(
                        target_node_ids=["2"],
                        conditions=[EdgeCondition(node_id="1", tag_value_name="NDA")],
                    ),
                ]
            )

        Example (AND case - multiple conditions):
            # Edge only followed when Document Type = Contract AND Region = US
            TaxonomyEdge(
                target_node_ids=["us_contract_node"],
                conditions=[
                    EdgeCondition(node_id="doc_type_node", tag_value_name="Contract"),
                    EdgeCondition(node_id="region_node", tag_value_name="US"),
                ],
            )
    ValidationError:
      properties:
        loc:
          items:
            anyOf:
              - type: string
              - type: integer
          type: array
          title: Location
        msg:
          type: string
          title: Message
        type:
          type: string
          title: Error Type
      type: object
      required:
        - loc
        - msg
        - type
      title: ValidationError
    TaxonomyNode:
      properties:
        node_id:
          type: string
          title: Node Id
        node_type:
          $ref: '#/components/schemas/TaxonomyNodeType'
          default: tag
        name:
          type: string
          title: Name
          description: The tag name
        description:
          anyOf:
            - type: string
            - type: 'null'
          title: Description
          description: >-
            Description of what this tag represents. Short and specific,
            capturing the relevant context.
        active_values:
          items:
            type: string
          type: array
          title: Active Values
          description: >-
            Allowed values for this tag. Empty list means all values from the
            tag definition are allowed.
      type: object
      required:
        - name
      title: TaxonomyNode
      description: >-
        A node in the taxonomy graph representing a tag.


        Nodes are tags with their metadata. The graph structure is defined

        by edges that connect parent nodes to child nodes with optional
        conditions.
    TaxonomyEdge:
      properties:
        edge_id:
          type: string
          title: Edge Id
        target_node_ids:
          items:
            type: string
          type: array
          title: Target Node Ids
          description: IDs of the child nodes
        conditions:
          items:
            $ref: '#/components/schemas/EdgeCondition'
          type: array
          title: Conditions
          description: >-
            Conditions that must ALL be true for this edge to be followed (AND
            logic)
      type: object
      required:
        - target_node_ids
        - conditions
      title: TaxonomyEdge
      description: >-
        An edge in the taxonomy graph connecting to child tags based on one or
        more conditions.


        For simple cases, use a single condition in the list.

        For AND cases, use multiple conditions - all must be satisfied.
    TaxonomyNodeType:
      type: string
      enum:
        - root
        - tag
      title: TaxonomyNodeType
      description: Types of nodes in a taxonomy graph
    EdgeCondition:
      properties:
        node_id:
          type: string
          title: Node Id
          description: ID of the node whose value must match
        tag_value_name:
          type: string
          title: Tag Value Name
          description: The tag value that must match
      type: object
      required:
        - node_id
        - tag_value_name
      title: EdgeCondition
      description: A single condition that must be met for an edge to be followed.
  securitySchemes:
    BasicAuth:
      type: http
      scheme: basic
    BearerAuth:
      type: http
      scheme: bearer
    UserIdAuth:
      type: apiKey
      in: header
      name: X-User-ID

````