[GH-ISSUE #3166] [BUG]: Try Swagger API POST /v1/document/upload with any file get 500 Error: Internal Server Error #2035

Closed
opened 2026-02-22 18:27:51 -05:00 by yindo · 3 comments
Owner

Originally created by @Fate369 on GitHub (Feb 10, 2025).
Original GitHub issue: https://github.com/Mintplex-Labs/anything-llm/issues/3166

How are you running AnythingLLM?

Docker (local)

What happened?

1、’[BUG]: Try Swagger API POST /v1/document/upload with any file get 500 Error: Internal Server Error
Image
2、Please see the attached error logs.
Image
3、I used a third-party tool to call this interface but still couldn't succeed
Image
4、Expect to get the success response

Are there known steps to reproduce?

No response

Originally created by @Fate369 on GitHub (Feb 10, 2025). Original GitHub issue: https://github.com/Mintplex-Labs/anything-llm/issues/3166 ### How are you running AnythingLLM? Docker (local) ### What happened? 1、’[BUG]: Try Swagger API POST /v1/document/upload with any file get 500 Error: Internal Server Error ![Image](https://github.com/user-attachments/assets/27db2a63-bd89-4009-9924-026fe1e311f2) 2、Please see the attached error logs. ![Image](https://github.com/user-attachments/assets/fda91805-c39e-45b6-8c71-ceb8fd918a73) 3、I used a third-party tool to call this interface but still couldn't succeed ![Image](https://github.com/user-attachments/assets/a1695d24-355d-40df-ac87-095b818d5715) 4、Expect to get the success response ### Are there known steps to reproduce? _No response_
yindo added the possible bug label 2026-02-22 18:27:51 -05:00
yindo closed this issue 2026-02-22 18:27:51 -05:00
Author
Owner

@JaySohagiyaOutamation commented on GitHub (Feb 19, 2025):

@Fate369 Can I know possible solution to this error, as I am getting same , Here you have closed this issue so could you please guide me into resolving this.

@JaySohagiyaOutamation commented on GitHub (Feb 19, 2025): @Fate369 Can I know possible solution to this error, as I am getting same , Here you have closed this issue so could you please guide me into resolving this.
Author
Owner

@timothycarambat commented on GitHub (Feb 19, 2025):

https://github.com/Mintplex-Labs/anything-llm/issues/2473#issuecomment-2427251301

Don't use the Swagger UI for file uploads. You should only be using it for documentation anyway - via code it works as expected and this is marked as wontfix.

If you are using the swagger UI, just use the regular UI. If you are testing uploads you would do it via code

@timothycarambat commented on GitHub (Feb 19, 2025): https://github.com/Mintplex-Labs/anything-llm/issues/2473#issuecomment-2427251301 Don't use the Swagger UI for file uploads. You should only be using it for documentation anyway - via code it works as expected and this is marked as wontfix. If you are using the swagger UI, just use the regular UI. If you are testing uploads you would do it via code
Author
Owner

@etcware commented on GitHub (Oct 10, 2025):

What does this mean? Is there any documentation other than /api/docs for uploading files? I'm trying to upload with the following code but I get status 200 and the response in HTML: I suppose it's due to an internal error but I don't know how to proceed.

import requests
import json
import os

class AnythingLLMClient:
    def __init__(self, base_url: str, api_key: str):
        """
        Inizializza il client per AnythingLLM
        
        Args:
            base_url: URL del server AnythingLLM (es: http://localhost:3001)
            api_key: La tua API key di AnythingLLM
        """
        self.base_url = base_url.rstrip('/')
        # print(self.base_url)
        self.api_key = api_key
        self.headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {api_key}'
        }
...
def _make_upload_request(self, folder_name: str, file_path: str, add_to_workspaces: str = None, metadata: dict = None):
        """
        Metodo helper per caricare un documento in una cartella specifica.
        
        Args:
            folder_name (str): Nome della cartella di destinazione.
            file_path (str): Percorso del file da caricare.
            add_to_workspaces (str, opzionale): Stringa con slug dei workspace separati da virgola.
            metadata (dict, opzionale): Dizionario di metadati per il documento.
        """
        print(folder_name)
        print(file_path)
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"File non trovato: {file_path}")
        
        # Costruisce l'URL per l'endpoint specifico
        url = f"{self.base_url}/api/document/upload/{folder_name}"
        print(url)
       # Prepara il payload per multipart/form-data
        form_data = {}
        files = {'file': (os.path.basename(file_path), open(file_path, 'rb'))}

        # Aggiungi i campi form-data se forniti
        if add_to_workspaces:
            form_data['addToWorkspaces'] = add_to_workspaces
        if metadata:
            form_data['metadata'] = json.dumps(metadata)  # Converti il dict in stringa JSON

        # Header: requests aggiungerà automaticamente 'Content-Type: multipart/form-data'
        headers = {'Authorization': f'Bearer {self.api_key}'}

        try:
            response = requests.post(
                url,
                files=files,
                data=form_data,
                headers={'Authorization': f'Bearer {self.api_key}'}
            )

            # STAMPA LA RISPOSTA COMPLETA
            print("\n📥 RISPOSTA COMPLETA DA ANYTHINGLLM")
            print("="*50)
            print(f"Status Code: {response.status_code}")
            print("Headers della Risposta:")
            for header, value in response.headers.items():
                print(f"  {header}: {value}")
            print("Body della Risposta (Testo):")
            print(response.text)
            
            # Tentativo di stampare come JSON se possibile
            try:
                print("\nBody della Risposta (JSON):")
                print(json.dumps(response.json(), indent=2))
            except json.JSONDecodeError:
                print("\nIl corpo della risposta non è un JSON valido, vedi testo sopra.")
            print("="*50)

            response.raise_for_status()
            return response.json()

        except requests.exceptions.RequestException as e:
            print(f"\n❌ Errore nella richiesta API: {e}")
            if 'response' in locals():
                print(f"Response Text: {response.text}")
            return None
        finally:
            files['file'][1].close() 
...
@etcware commented on GitHub (Oct 10, 2025): What does this mean? Is there any documentation other than /api/docs for uploading files? I'm trying to upload with the following code but I get status 200 and the response in HTML: I suppose it's due to an internal error but I don't know how to proceed. ``` import requests import json import os class AnythingLLMClient: def __init__(self, base_url: str, api_key: str): """ Inizializza il client per AnythingLLM Args: base_url: URL del server AnythingLLM (es: http://localhost:3001) api_key: La tua API key di AnythingLLM """ self.base_url = base_url.rstrip('/') # print(self.base_url) self.api_key = api_key self.headers = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {api_key}' } ... def _make_upload_request(self, folder_name: str, file_path: str, add_to_workspaces: str = None, metadata: dict = None): """ Metodo helper per caricare un documento in una cartella specifica. Args: folder_name (str): Nome della cartella di destinazione. file_path (str): Percorso del file da caricare. add_to_workspaces (str, opzionale): Stringa con slug dei workspace separati da virgola. metadata (dict, opzionale): Dizionario di metadati per il documento. """ print(folder_name) print(file_path) if not os.path.exists(file_path): raise FileNotFoundError(f"File non trovato: {file_path}") # Costruisce l'URL per l'endpoint specifico url = f"{self.base_url}/api/document/upload/{folder_name}" print(url) # Prepara il payload per multipart/form-data form_data = {} files = {'file': (os.path.basename(file_path), open(file_path, 'rb'))} # Aggiungi i campi form-data se forniti if add_to_workspaces: form_data['addToWorkspaces'] = add_to_workspaces if metadata: form_data['metadata'] = json.dumps(metadata) # Converti il dict in stringa JSON # Header: requests aggiungerà automaticamente 'Content-Type: multipart/form-data' headers = {'Authorization': f'Bearer {self.api_key}'} try: response = requests.post( url, files=files, data=form_data, headers={'Authorization': f'Bearer {self.api_key}'} ) # STAMPA LA RISPOSTA COMPLETA print("\n📥 RISPOSTA COMPLETA DA ANYTHINGLLM") print("="*50) print(f"Status Code: {response.status_code}") print("Headers della Risposta:") for header, value in response.headers.items(): print(f" {header}: {value}") print("Body della Risposta (Testo):") print(response.text) # Tentativo di stampare come JSON se possibile try: print("\nBody della Risposta (JSON):") print(json.dumps(response.json(), indent=2)) except json.JSONDecodeError: print("\nIl corpo della risposta non è un JSON valido, vedi testo sopra.") print("="*50) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: print(f"\n❌ Errore nella richiesta API: {e}") if 'response' in locals(): print(f"Response Text: {response.text}") return None finally: files['file'][1].close() ... ```
yindo changed title from [BUG]: Try Swagger API POST /v1/document/upload with any file get 500 Error: Internal Server Error to [GH-ISSUE #3166] [BUG]: Try Swagger API POST /v1/document/upload with any file get 500 Error: Internal Server Error 2026-06-05 14:44:08 -04:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: Mintplex-Labs/anything-llm#2035