Appwrite Function not Receiving Payload in context.req.body

159 views Asked by At

I am using Appwrite functions to handle some backend tasks. I've set up an HTTP-triggered function to receive a JSON payload containing "name" and "company". When I send a POST request with the expected data using Postman or curl, the function does not seem to capture the data in context.req.body.

This is my main function:

import json
import os

from appwrite.client import Client
from appwrite.services.databases import Databases
from appwrite.id import ID

def init_client():
    client = Client()
    client.set_endpoint(os.environ['ENDPOINT_URL'])
    client.set_project(os.environ["APPWRITE_FUNCTION_PROJECT_ID"])
    client.set_key(os.environ["APPWRITE_API_KEY"])
    return client

def add_to_collection(name, company):
    client = init_client()
    database = Databases(client)

    try:
        database.create_document(
            database_id="visitors",
            collection_id="qr-code-form",
            document_id=ID.unique(),
            data={
                'name': name,
                'company': company
            }
        )
    except Exception as e:
        context.error("Failed to create document: " + e.message)
        return context.response.send("Failed to create document")

    return context.response.send("Document created")


def main(context):
    # Log the raw request body
    context.log(context.req.body)
    
    # Attempt to parse it
    try:
        data = json.loads(context.req.body)
    except json.JSONDecodeError:
        context.error("Invalid JSON received.")
        return context.res.empty()

    name = data.get("name")
    company = data.get("company")
    
    if not name or not company:
        context.error({"success": False, "message": "name or company not provided"})
        return context.res.empty()

    try:
        response = add_to_collection(name, company)
        context.log({"success": True, "data": response})
        return context.res.json({"success": True, "data": response})
    except Exception as e:
        context.error({"success": False, "message": str(e)})
        return context.res.empty()

I added the payload in the body in Postman: Body of Post-Request

Every time I call the function via Postman, I receive Invalid JSON received. Indeed, when logging the content of the body, it is an empty string.

I tried to use cURL, too, with this command, but same behavior:

curl --location 'https://XXXX.com/v1/functions/XXXX/executions' \
--header 'X-Appwrite-Project: XXXX' \
--header 'X-Appwrite-Key: XXXXX' \
--header 'Content-Type: application/json' \
--data '{
    "name": "John",
    "company": "XYZ Corp"
}'
1

There are 1 answers

1
user2335427 On BEST ANSWER

If you are using Appwrite self-hosted, update it.

There is a fix on version 1.4.7 solving missing body con "context.req".

https://github.com/appwrite/appwrite/pull/6988