Send JSON with python to API

Asked

Viewed 409 times

0

I’m putting together a list of objects to post to an API in made in Arabic, but I can’t convert the data to work on the API. In python the list of objects is something like:

payload = [
    {"nome":"Flávio", "email":"[email protected]"},
    {"nome":"novo", "email":"[email protected]"}
]

I’m using the python request library to send: Code of the python script

headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0',
    'Authorization': token
}

requests.post(url, data=json.dumps(payload), headers=headers)

In API with Laravel I get so:

public function imporUsers(Request $request)
{
    $data = ($request->getContent());
    return $data;
}

But the answer I have is a Sring equal to payload I informed the above and I can’t get the data with a $data[0]['nome'] for example. I tried to make a json_decode, but it gives an error saying that the entered parameter is wrong.

I need to turn this string into a php array to access the key and value.

  • Try to change the Content-type for application/json

2 answers

1


An example of sending json to the PHP server

data = json.dumps(
        {
            exemple:
            {
                'chave':'Valor',
                'chave':'Valor'
            }
        }
    )

response = requests.post(URL_WEBSERVICE, data = data, timeout=TIMEOUT_POST, headers=headers)

In the controller on the Laravel

    public function foo(Request $request){
        $json_recebido = $request->json();
        //dd($json_recebido);
    }
  • Oops, vlw bro. I needed to do json_dumps when adding the object to the list. Another problem tbm is that my array was wrong. One of the values was returning NAN and did not recognize when trying to make json_decode.

-1

Do the following test:

requests.post(url, json=payload, headers=headers)

Using the parameter json in the request, will change the Content-Type in the header for application/json.

  • Could explain what differs this form from what he asked in the question?

  • Using the json Parameter in the request will change the Content-Type in the header to application/json.

  • Exactly this information is missing in your answer to justify the :D solution (in Portuguese, preferably)

  • I’ve tried it but it didn’t work. I can send and receive the data in the api. Only q comes a string and I can’t list all the objects inside it

Browser other questions tagged

You are not signed in. Login or sign up in order to post.