Home > Mobile >  How to send a POST request to Swagger API on a localhost with Python?
How to send a POST request to Swagger API on a localhost with Python?

Time:10-09

I'm trying to send a post request to a Swagger API, which is currently on the localhost and keep getting various errors.

The error I'm getting at the moment is: requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

The code I'm executing:

import requests 
import json 

def create_bucket():

    url = "http://127.0.0.1:3000/api/buckets"

    headers = {
        "content-type": "application/json"
    }

    params = {
        "bucket_name": "test_bucket"
    }

    response = requests.post(url=url, headers=headers, params=params)

    print(response.json())

create_bucket()

What am I doing wrong?

Edit:

Tried printing response.content as per request and got an error: b'<!doctype html>\n<html lang=en>\n<title>400 Bad Request</title>\n<h1>Bad Request</h1>\n<p>Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)</p>\n'

Edit 2:

Solved the problem. Correct approach:

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

CodePudding user response:

Per the error, need to encode json properly, try:

response = requests.post(url=url, headers=headers, json=params)

requests will do the right thing

or

response = requests.post(url=url, headers=headers, params=json.dumps(params))
  • Related