Search code examples
djangolua

set a value in request body from lua script on kong


I am using kong as API gateway and running a lua script to modify my api request. In my API request from server I expect, a authorization token & content type in header.

I wish to add a field, user_id in my API request body. How can I do that?

my request from server has only authorization & content-type as you can see in the image (click here)

also my body has nothing from server as you can see in image (click here)

but I want to add user_id in this Api request body(raw) via lua script.

P.s. I am then reading the body in my django application as request_body = json.loads(request.body.decode('utf-8'))

pls guide.

in my lua script I am trying

local form_data, err, mimetype = kong.request.get_body()
form_data["customer_id"] = customer_obj.user_id
form_data = cjson.encode(form_data)
kong.service.request.set_raw_body(form_data)

I get

{
    "message": "An unexpected error occurred" }

in response with the above code.


Solution

  • solved the issue. basically, I was trying to fetch the request body but since it was blank & nothing was coming from the server in the body, it generated the error.

    So I only set my user_id in the request body & also modified the way of reading the body in my Django app since now json encoding won't be required.

    kong.service.request.set_raw_body({user_id = customer_obj.user_id})
    

    in Django, read raw data as request.data