I can't call a FastAPI POST route using Python's "requests" module, but I'm able to call the same route via cURL command line

15 views Asked by At

Below you can find (the relevant excerpt of) my "server-side" FastAPI code.

from fastapi import FastAPI, UploadFile, HTTPException
from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
from pydantic import BaseModel

qh = os.getenv('QDRANTHOST','qdrant')
qc = os.getenv('QDRANTCOLL','documents')

class QdrantQuery(BaseModel):
    query: str
    host: str | None = qh
    collection: str | None = qc

def execute(question: str, host: str, collection: str):
    index = qdrant_index(qdranthost=host,collection=collection)
    query_engine = index.as_query_engine(similarity_top_k=int(similarity),response_mode=responsemode)
    return query_engine.query(question)

@app.post("/query")
async def query(input: QdrantQuery ):
    question = input.query
    host = input.host
    collection = input.collection
    result = execute(question,host,collection)
    return result

When I call this code from a BASH shell, with this command line:

curl -H 'content-type: application/json' -d '{"query": "Chi è Blair Clarimonde?","collection": "documents"}' http://localhost:9999/query

It works perfectly. However, when calling from within a Streamlit frontend, through requests module... I keep getting 422 error codes

queryurl = f"http://dctvllm01.upgrade.lan:9999/query"
headers={"Content-type": "application/json"}
a = {"question": "Chi è Blair Clarimonde?","collection": "documents"}
b = json.dumps(a)
r = requests.post(url=queryurl,data=b, headers=headers)
print(r.text)

Error detail:

{"detail":[{"type":"missing","loc":["body","query"],"msg":"Field required","input":{"question":"Chi è Blair Clarimonde?","collection":"documents"},"url":"https://errors.pydantic.dev/2.6/v/missing"}]}

Could someone point out the fault in my "client-side" code? Thanks.

0

There are 0 answers