Encountering a 400 error while making a Python request that involves

Below is the code I am using to register a user through an API endpoint:


import argparse
import requests
import ConfigParser
import json
import sys
import logging

# Configuration Parameters
env = 'Pre_internal'

Config = ConfigParser.ConfigParser()
Config.read("../etc/config.ini")
endpoint = Config.get(env, 'endpoint')
admin_user = Config.get(env, 'admin_user')
admin_password = Config.get(env, 'admin_password')

# Logging Config
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(levelname)s %(name)s %(message)s',
                    filename='../logs/create_user.log')

# Functions
def post(login, email, password):
        login_ok = login.lower()

        data = {"login": login_ok, "email": email, "password": password}
        headers = {'Content-Type': 'application/json'}
        create_user = requests.post(endpoint, data=json.dumps(data), headers=headers, auth=(admin_user, admin_password))

        if create_user.status_code == 202:
            print 'User has been created successfully'
            logging.info('User has been created successfully %s', login_ok)
            sys.exit(0)
        else:
            print 'Error Received: ', create_user
            logging.error('Received error when creating the user %s %s', login_ok, create_user)
            sys.exit(1)

# Main
parser = argparse.ArgumentParser(description='''Script to create users in Cloud Storage''', epilog='''Example: ./cs-create-user.py -l dsmc -e <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="345047595774405d501a5147">[email protected]</a> -p changeme''' )

parser.add_argument('-l', '--login', help='Login account')
parser.add_argument('-e', '--email', help='Email account')
parser.add_argument('-p', '--password', help='Password account')
args = parser.parse_args()

if not args.login:
    print 'Login incomplete'
if not args.password:
    print 'Password incomplete'
if not args.email:
    print 'Email incomplete'
else:
    post(args.login, args.password, args.email)

After three hours, I keep receiving a 400 error. I suspect it's due to the JSON format - any insights on why this might be happening?

Your assistance would be greatly appreciated.

Thank you in advance.

Answer №1

I recently tackled this issue with the assistance of a helpful tool called . To start, I replicated your curl command for sending data there:

curl -v -u aa:bb -X POST httpbin.org/post -H "Accept: application/json; version=0" -H "Content-Type:application/json" -d '{"login": "username", "password": "secret", "email":"my_email"}'

The output from this command was as follows:

{
  "args": {}, 
  "data": "{\"login\": \"username\", \"password\": \"secret\", \"email\":\"my_email\"}", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "application/json; version=0", 
    "Authorization": "Basic YWE6YmI=", 
    "Content-Length": "63", 
    "Content-Type": "application/json", 
    "Host": "httpbin.org", 
    "User-Agent": "curl/7.43.0"
  }, 
  "json": {
    "email": "my_email", 
    "login": "username", 
    "password": "secret"
  }, 
  "origin": "197.155.4.24", 
  "url": "http://httpbin.org/post"
}

Next, I made adjustments to your code to send a similar request using argparse for passing arguments. The response I received had similarities. By comparing the two outputs using PyCharm's 'Compare with Clipboard' feature, I quickly identified the issue:

https://i.stack.imgur.com/yEzTD.png

Your code had mistakenly interchanged the positions of password and email fields! Apologies for the oversight.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unraveling the complexities of parsing multi-tiered JSON structures

I am struggling with indexing values from a multi-level JSON array. Here is the JSON data in question: { "items": [ { "snippet": { "title": "YouTube Developers Live: Embedded Web Player Customization" } ...

Is it possible to transform multiple input values into a JSON array using PHP?

I am working on a task to convert various input values into a JSON array using PHP. Here is the form structure: <input name="title[]"> <input name="description[]"> <input name="total[]"> This is the desired ...

What is the best way to use requests in python to enter text in a textarea, then scrape the html with bs4, all while the input remains hidden?

I'm working on a script that interacts with by sending a string and receiving one or all of the "fancy text" variations provided by the site. I am struggling to identify the input area within the HTML structure, especially since I aim to use requests ...

Converting int arrays into JSON for Spring RequestBody handling

I am facing an issue with my Spring controller method that requires a @RequestBody as a parameter. The structure of the request body class is like this: public class myClass { CustomObject obj int x int y int[] values Character c ...

Extracting Data from JSON Structures

I am struggling with extracting data from a JSON string that looks like this: var txt= '{“group”: [ {“family1”: { “firstname”:”child1”, “secondname”:”chlid2” }}, {“family2”: { ...

What is the most efficient method for retrieving an element using a data attribute with an object (JSON) value?

Imagine having the following HTML element: <div class='element' data-info='{"id":789, "value":"example"}'></div> By running this JavaScript code, you can access the object stored in the data attribute. console.log($(&apos ...

Executing Mustache templates with JSON or Strings in Android can be achieved by following these steps

I possess a String object with a template foundation, similar to this: <h1>{{header}}</h1> {{#bug}} {{/bug}} {{#items}} {{#first}} <li><strong>{{name}}</strong></li> {{/first}} {{#link}} <li><a h ...

Building a table using jQuery and adding elements using JavaScript's append method

Greetings! I've been attempting to add new records from a form that registers or updates student information, but unfortunately it doesn't seem to be functioning correctly. Can anyone point me in the right direction as to why this may be happenin ...

What is the best way to transfer JSON data to a different controller in AngularJS?

Hello, I'm still learning AngularJS and facing an issue with the following code snippet. app.config(function($routeProvider) { $routeProvider .when('/', { templateUrl: "partials/home.html", controller: "mainControlle ...

Expanding the dimensions of both 3D and 2D array

Currently, I am faced with a challenge involving a 3D array of shape (3, 4, 3) and a 2D array of shape (3, 3). My objective is to multiply these arrays in such a way that the ith element of the resulting 3D array corresponds to the product of the ith eleme ...

What is the best source for JSON serialization when using Ktor?

Having some trouble sending requests with Kotlin through Ktor. Android Studio doesn't seem to recognize the JSON serialization imports I'm trying to use. Here are the dependencies in my build.gradle.kts (:app): implementation("io.ktor:ktor- ...

[AWS Lambda SDK] - Executing Lambda Function - Processing Payload Response as Unit8Array - Conversion to String

Currently, I am utilizing the npm package @aws-sdk/client-lambda to invoke Lambdas. In my setup, I have two Lambdas - Lambda A and Lambda B, with Lambda A responsible for invoking Lambda B. The invocation of Lambda B from Lambda A is done through the foll ...

Issue with JSON parsing on non-Chrome web browsers

Encountering a problem with parsing fetched JSON data from browsers other than Chrome, Firefox providing error message: "SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data". Notably, code functions in local node.js environmen ...

Selenium can be utilized to scrape data from multiple pages by automating the process of

I'm currently working on a Selenium script to extract all filenames from every directory on a website. My strategy involves creating a list of directory objects and iteratively clicking on each directory in the list to access the filenames. However, a ...

Tips for installing npm packages using a python script in the same directory as my script

The desired file structure should resemble this: test.py node_modules (Folder containing installed npm modules) Here is the attempted solution: import subprocess import os dir_path = os.path.dirname(os.path.realpath(__file__)) # Retrieve the directory ...

Utilizing PHP to send arrays through AJAX and JSON

-I am facing a challenge with an array in my PHP file that contains nested arrays. I am trying to pass an integer variable (and may have to handle something different later on). -My objective is to make the PHP file return an array based on the incoming v ...

Using PDO to retrieve data from a mysql database table stored in innodb format, the query fails if the field values contain apostrophes

Utilizing prepared queries and binding variables to placeholders has been effective for inserting data without issues. However, a concern arose when the registration form received a value like St. John's in a field. The data was successfully written, ...

Automatically input the city once the zip code has been entered

Trying to automatically fill in the CITY: field when entering the zip code results in an "undefined variable: array on line.." error where value="< ? php $array['navn'] "> Is there anyone who can provide assistance with this issue? View scr ...

Iterating through a list in Python to check if an item exists in a line

I need to iterate through two lists and only print an item if it is present in the second list. However, I am working with very large files and do not want to load them into memory as a list or dictionary. Is there a method to achieve this without storing ...

Transform into dynamic types in Java

Today, I'm facing a challenge with JSON data that consists of an array of objects. Each object in the array contains two properties: type and value. [{ "type": "Boolean", "value": false }, { "type": "String[]", "value": ["one", "two", ...