Search code examples
pythonhttpx

Why my API request with httpx not working?


I tested my request to API with postman.co.

But this request not working when I try run it with httpx library for Python. There's my request.

enter image description here Params:

enter image description here

Full Python code:

import httpx
import ujson

headers = {
    'Accept': 'application/vnd.yclients.v2+json',
    'Content-Type': 'application/json',
    'Authorization': f'Bearer {bearer_key}, User {user_key}'
}
params = {
    "staff_id": staff_id,
    "services": [
        {
            "id": service_id
            }
        ],
    "client": {
        "name": "client_name",
        "phone": "**********111"
        },
    "datetime": "2023-07-04T09:00:00+03:00",
    "seance_length": 600
}

company_id = {company_id} # hided id
record_id = {record_id} # hided id

url = 'https://api_url.com/api/{}/{}'.format(company_id, record_id)
session = httpx.Client()
response = session.put(url, headers=api.headers, params=params)
first_request =  ujson.loads(response.text)

For my code I get error:

{'success': False,
 'data': None,
 'meta': {'message': 'An error has occurred',
  'errors': {'id': ['The required id parameter was not passed.']}}}

Why tested and 100% right request runs with error?


Solution

  • Because the request you're testing is not the one your code is sending, and hence is not 100% right.

    You're using params= for what is your body data; that's for query parameters.

    Use json=... instead to have httpx encode your params to JSON and send 'em.

    response = session.put(url, headers=api.headers, json=params)