Home > Net >  Request API POST
Request API POST

Time:02-05

I'm having a problem with a Python request, where I pass the body url to the API data.

Note: I have a Node.js project with TypeScript that works normally, prints to the screen and returns values. However if I try to make a request in Python it doesn't work with an error 401.

Below is an example of how the request is made in Python. can you help me?

import requests

url = 'https://admins.exemple'

bodyData = {
    'login': 'admins',
    'pass': 'admin',
    'id': '26' }

headers = {'Content-Type': 'application/json'}

resp = requests.post(url, headers=headers, data=bodyData)

data = resp.status_code

print(data)

CodePudding user response:

Please dump a dict to a json string as follows:

import json

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

Upd:

You also can pass your dict to json kwarg

resp = requests.post(url, headers=headers, json=bodyData)

It will set Content-Type: application/json and dump dict to json automatically

CodePudding user response:

You are not correctly authenticating with the server. Usually, you need to send the username and password to a "sign in" route which will then return a token. Then you pass the token with other requests to get authorization. Since I don't know any details about your server and API, I can't provide any more details to help you out.

  •  Tags:  
  • Related