How to post a request with python specifying the body raw - python

I am trying to send a JSON object using python but I am getting 422 error. Meanwhile, with postman I am able to post the JSON via the API:
First I enter the authentication in the Authorization and in the body I specify raw and choose JSON then I post the JSON object and get a 200 response.
But with python:
endpoint = "some endpoint"
url = host + endpoint
headers={"Accept": "application/json",
"Authorization": f"Bearer {bearer_token}"}
order = json.dumps(json_object, ensure_ascii=False)
send_data = requests.post(url, json=order, headers=headers)
print(send_data.json())
if send_data.status_code==200:
print("Order successfully sent")
else:
print(f"The following error was encountered. Error: {send_data.status_code}")
What could be wrong? please advise

try
headers={"Accept": "application/json",
"Authorization": f"Bearer {bearer_token}"}
send_data = requests.post(url, data=order, headers=headers)

Related

Regarding the new Bit.ly API in Python

Seemingly the bit.ly API has been updated a lot in recent years. Here is the website of the latest API documentation https://dev.bitly.com/api-reference
I am trying to do the simplest operation, i.e., shortening a long URL.
I have generated a token following the instructions, and below is the code I tried following the example (https://dev.bitly.com/api-reference/#createBitlink) where I used my token instead of the string "my token" here:
import requests
headers = {
"Authorization": "Bearer {my token}",
"Content-Type": "application/json",
}
data = '{ "long_url": "https://dev.bitly.com", "domain": "bit.ly"}'
response = requests.post(
"https://api-ssl.bitly.com/v4/shorten", headers=headers, data=data
)
But the response is 403.
Is there anyone who is familiar with the bit.ly API?
Any help will be appreciated!
A related question: getting bit.ly to return shortened URL
Sorry for the confusion...
It is seemingly okay now.
Below is an example extended from https://dev.bitly.com/api-reference/#createBitlink
import requests
import sys
input_url = sys.argv[1]
longurl = "https://" + input_url if not input_url.startswith("https://") else input_url
print(longurl)
token = "find your token at https://app.bitly.com/settings/api/"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
data = '{ "long_url": "' + longurl + '", "domain": "bit.ly"}'
# print(data)
response = requests.post(
"https://api-ssl.bitly.com/v4/shorten", headers=headers, data=data
)
try:
print(response.json()["link"])
except:
print(response)
print(response.json())
python bitly.py https://stackoverflow.com/questions/75279574
https://stackoverflow.com/questions/75279574
https://bit(dot)ly/3DqI7Ea

How to resolve Bad Requests in python (pycharm)?

I am working on the requests library in python where I am requesting the API of Bugzilla. The API works fine in postman but the script which I have written from the below link is not working and sending the response back as Bad Request 400. I have added the code below.
Get bugs from bugzilla using python
import requests
import json
URL = 'https://bugzilla.mozilla.org/rest/bug/35'
API_KEY = "api_key"
headers = {
"content-type": "application/json"
}
params = {
"api_key": API_KEY,
}
try:
response = requests.get(URL, headers=headers, params=params)
if response.status_code != 200:
print(f'error : {response.status_code}')
print(response.reason)
else:
print('Success')
print(json.load(response.text))
except response:
print(response)
Probably you are sending wrong api key
try to get your api key via:
r = requests.get('https://bugzilla.mozilla.org/rest/login?login=username&password=password')
r.text
https://wiki.mozilla.org/Bugzilla:REST_API

REST API post request results in successful request but not creation

I've been trying to make a Post Request to my CRM API. The CRM API is very vague:
"You can use POST request when you wish to create records. You POST a JSON encoded string to the servers and it will return a single instance of the record."
POST /{object_name}
Example:
Request URL (POST):
/accounts
Request Body (JSON):
{
"name": "testing API"
}
I've had plenty of success making GET requests regularly, but POST is not working out so easily.
url = "https://apiv4.reallysimplesystems.com/accounts?<KEY>"
payload = {"name":"Ziggy","owner":"XYZ","addresscounty/state":"Awe","source":"Space"}
headers = {
'Content-Type': 'application/json',
'Cookie': 'XSRF-TOKEN=<TOK>; really_simple_systems_session=<KEY>'
}
response = requests.post(url, headers=headers, data=payload)
I get a status code 200 when I run this, but I'm really looking for that 201. The only clue that I've got to follow at this point is that when I run:
response.json()
I get the error:
JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I've tried switching the response parameters to json:
response = requests.post(url, headers=headers, json=payload)
I've tried ensuring that my payload is json by using json.dumps():
payload = {"name":"Ziggy","owner":"XYZ","addresscounty/state":"Awe","source":"Space"}
payload = json.dumps(payload)
And I've tried all sorts of other shenanigans that I can't even recall at this point. Does anyone have any idea where I'm going wrong here? The 200 status code makes me feel painfully close.
Replace <AUTH_TOKEN> with your auth token
url = "https://apiv4.reallysimplesystems.com/accounts/"
payload = {"name":"Ziggy"}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer <AUTH_TOKEN>',
}
response = requests.post(url, headers=headers, data=payload)
Problem solved:
import json
import requests
url = "https://apiv4.reallysimplesystems.com/accounts"
payload = {"name":"RSS Test Joe Bloggs","addresscounty/state":"Maryland","source":"Word of Mouth"}
payload = json.dumps(payload)
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer <AUTH KEY>'
}
response = requests.post(url, headers=headers, data=payload)
Rather than using Postman's code which included the in the URL and used :
'Cookie': 'XSRF-TOKEN=<TOK>; really_simple_systems_session=<KEY>'
I replaced it with a standard Authorization header. Secondly, I found that using json.dumps(payload) and json = payload was resulting in a Bad Request.

Django post request data

Im trying to post data to my Django server but when I check the server the Querydict is empty. When I call from the browser it does look good.
import requests
import json
headers = {
"AUTHORIZATION": "1234",
"Content-type": "application/json",
"Accept": "text/plain"
}
print headers
payload = {
"start_date_s":"04/01/2016",
"start_date_e":"04/15/2016"
}
r = requests.post('http://localhost:8000/get-ticket-data',headers=headers, json = json.dumps(payload))
print r.content
print r.text
If you use the json argument, you should pass your dict as is, don't dump it (docs):
r = requests.post('http://localhost:8000/get-ticket-data',headers=headers, json=payload)
if you send json request, you need to use request.body in django view to get the that, not request.POST

Python Requests Code 141 Error

I'm trying to use requests in python to post a json dictionary to a url. I need to get a string back from the url but I keep getting a code 141 error -{"code":141,"error":"Missing a github repository link"}. I'm using this website(http://docs.python-requests.org/en/latest/user/quickstart/) to do requests.
Any ideas on why I keep getting that error? Code is below.
import requests
import json
payload = { "email" : "jade#gmail.com", "github" : "https://github.com/"}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/register", params = payload, headers = headers)
print(r.url)
print r.text
Update: The suggestion worked but now I'm getting an{"code":141,"error":"success/error was not called"} error when I try to save the response I recieve from the url into a variable and then post it back to a different url.
#Store the token into a variable
token = r.text
payload = { "token" : token}
headers = {'content-type': 'application/json', "Accept": 'application/json'}
r = requests.post("http://challenge.code2040.org/api/getstring", json = payload, headers = headers)
print r.text
Since you are making a POST request and you need to provide a JSON in the request body, use json argument, not params:
r = requests.post("http://challenge.code2040.org/api/register",
json=payload,
headers=headers)
(tested - got back a token)
Note that json argument was introduced in requests 2.4.2.

Categories

Resources