Home > Forum > Actions > Send Attachment using POST method API

Send Attachment using POST method API
0

Hi everyone,

I am trying to upload an attachment using the REST API. I am using the REST Web service action for this. How to do it correctly? Along with the attachment, I would also like to upload a json with other information. Endpoint is configured correctly, the problem is in the BODY itself. The referenced API is written in python using FastAPI framework.

This is response:

{
"detail": [
{
"type": "missing",
"loc": [
"body",
"id"
],
"msg": "Field required",
"input": null,
"url": "https://errors.pydantic.dev/2.6/v/missing"
},
{
"type": "missing",
"loc": [
"body",
"category"
],
"msg": "Field required",
"input": null,
"url": "https://errors.pydantic.dev/2.6/v/missing"
},
{
"type": "missing",
"loc": [
"body",
"file"
],
"msg": "Field required",
"input": null,
"url": "https://errors.pydantic.dev/2.6/v/missing"
}
]
}

API code:

class PDFItem(BaseModel):
"""
A model representing a PDF item with an ID, category, and file.

Attributes:
- id (int): The unique identifier of the PDF item.
- category (Category): The category of the PDF item, as defined in the Category enum.
- file (UploadFile): The uploaded PDF file.
"""

id: int
category: Category
file: UploadFile = File(...)

---------------------
@app.post("/pdf_text")
async def pdf_text(item: PDFItem = Depends(pdf_item_form)) -> dict[int, dict[str, str]]:
pdf_text = get_text_from_pdf(item.file.file)
logger.info(f"Extracted text for PDF item with id: {item.id}")
return {item.id: {"text": pdf_text}}
--------------------
def pdf_item_form(
id: int = Form(...),
category: Category = Form(...),
file: UploadFile = File(...)
) -> PDFItem:
"""
Form parser to create a PDFItem object from form data.

Args:
- id (int): The unique identifier of the PDF item.
- category (Category): The category of the PDF item, as defined in the Category enum.
- file (UploadFile): The uploaded PDF file.

Returns:
PDFItem: An instance of PDFItem populated with form data.
"""
return PDFItem(id=id, category=category, file=file)

MVP

Hi,

I'm sorry, but I for my part don't understand the posted code and I'm also not sure, that you actually can have:
- a request of content-type:application/json
- set the request to multipart
- and provide a binary part

For me this doesn't fit together, but I'm not an expert here.

Did you make it work without WEBCON for example with postman or a local test?
If it's working locally I would use https://httptoolkit.com/ to take an actual look at the send request.

If you have the source code under your control, I would probably switch to pure JSON and provide the file content as Base64. Here's an exmaple:
https://daniels-notes.de/posts/2023/copy-attachment-to-other-workflow#generate-the-body

Best regards,
Daniel