Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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))

>Solution :

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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading