Babayega
Babayega

Reputation: 33

How do I pass a variable into a payload

So I have an endpoint that I am trying to integrate in Python which accepts a POST request and according to the API documentation, the payload is to be formatted this way:

payload = "{\r\n\"serviceCode\" : \"V-TV\",\r\n\"type\" : \"DSTV\",\r\n\"smartCardNo\" : \"10441003943\"\r\n}\r\n\r\n\r\n\r\n\r\n"

I want the values of type and smartCardNo to be dynamic, i.e I am going to get the values from a form in the frontend and pass it to the backend but I am finding it difficult to do so. If I format the payload this way(which of course allows ease of passing variable):

{
        "serviceCode": "V-TV",
        "type": "DSTV",
        "smartCardNo" : "10441003943"
  }

I get this error:

{'required_fields': ['The service code field is required.'], 'message': 'Service Code is not supplied', 'status': '301'}

Could anyone tell me how I can pass the values for type and smartCardNo dynamically in the fist format(the format specified in the documentation)....any help will be greatly appreciated.

Upvotes: 0

Views: 871

Answers (1)

Everton Reis
Everton Reis

Reputation: 442

you can simply use the .format()

dict_values = {
        "serviceCode": "V-TV",
        "type": "DSTV",
        "smartCardNo" : "10441003943"
  }
    
payload = """{{"serviceCode":"{serviceCode}","type":"{mytype}","smartCardNo":"{smartCardNo}"}}""".format(
        serviceCode = dict_values["serviceCode"],
        mytype = dict_values["type"],
        smartCardNo = dict_values["smartCardNo"]
    )

output:

'{"serviceCode":"V-TV","type":"DSTV","smartCardNo":"10441003943"}'

If you really need the same format as in your payload example, simple use:

payload = "{{\r\n\"serviceCode\" : \"{serviceCode}\",\r\n\"type\" : \"{mytype}\",\r\n\"smartCardNo\" : \"{smartCardNo}\"\r\n}}\r\n\r\n\r\n\r\n\r\n".format(
    serviceCode = dict_values["serviceCode"],
    mytype = dict_values["type"],
    smartCardNo = dict_values["smartCardNo"]
)

and your output will be:

'{\r\n"serviceCode" : "V-TV",\r\n"type" : "DSTV",\r\n"smartCardNo" : "10441003943"\r\n}\r\n\r\n\r\n\r\n\r\n'

Upvotes: 2

Related Questions