I am trying to send a JSON payload with session request in python to a PHP server.
The session itself is established and cookies are accepted by the server but when I print out the $_POST, it returns an empty array.
It looks like the payload is not being sent with the request or maybe PHP doesn't recognize it.
Client Side - Python:
import json
import requests
url = 'https://prov.is.st.com/eventpost.php'
payload = {
'script': 'pyt.sh',
'status': 'Success'
}
s = requests.Session()
s.cookies.set('provisioning', cookie, domain='prov.is.st.com')
headers = {
'Content-Type': 'application/json'
}
s.headers.update(headers)
response = s.post(url, data=payload, verify=False)
print(response.text)
Server Side - PHP:
<?php
print_r($_POST);
if(isset($_POST['status'])){
$status = $_POST['status'];
}
else{
$status=0;
}
if (isset($_POST['script'])) {
$script=$_POST['script'];
} else {
$script="unknown";
}
if (isset($_COOKIE['provisioning'])) {
$cookie=$_COOKIE['provisioning'];
print "OK: Message accepted: [$status][$script]\n";
}
else {
print "ERROR: NO cookie provided.\n";
}
Output
Array
(
)
OK: Message accepted: [0][unknown]
As per the documentation here: https://2.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests, in order to post JSON data, you should use either of the following ways:
import json
...
response = s.post(url, data = json.dumps(payload), verify = False)
or
...
response = s.post(url, json = payload, verify = False)
Note, the json parameter is ignored if either data or files is passed.
Using the json parameter in the request will change the Content-Type in the header to application/json.
Related
I am trying to post/put to Sheety via Python:
SHEETY_URL = "https://api.sheety.co/gfhgfhjfdghjgfjf/flightDeals/prices/5"
header = {
"Content-Type" : "application/json"
}
params_sheety = {
"price": {
"iataCode": "PLN"
}
}
response_sheety = requests.put(url=SHEETY_URL, params=params_sheety, headers=header)
print(response_sheety)
print(response_sheety.json())
=======================================================
Getting Bad request Error:
<Response [400]> {'errors': [{'detail': "Bad Request. The JSON payload
should be inside a root property called 'price'. Check
https://sheety.co/docs for more details."}]}
The same request works fine with Postman.
When you use params=params_sheety, the parameters are not sent as json.
Use json=params_sheety to send them as json.
This also sets the content-type header to json automatically, so you don't need headers=header.
I have no idea where is error. My response is 400 cuz of it:
"errors":{"data":["The data field is required."
but i am sending 'data':
data = "{'example': 'example'}"
url = f'http://localhost:5219/myApi'
payload = {'data': str(data).encode('utf-8')}
req = requests.post(url, data=payload)
print(req.content)
response
b'{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-355ed090aff5fa10460587fe222edbbe-3b3927cf18b26b78-00","errors":{"data":["The data field is required."]}}'
how can i repair that?
i tried changing formats and other things but it didn't work pls help me
this is c# code from api:
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using System.Text.Json.Nodes;
namespace spyware.Api.Controllers
{
[Route("[controller]")]
[ApiController]
public class api : ControllerBase
{
[HttpPost]
public void GetResponse(string data)
{
Console.WriteLine(JsonConvert.DeserializeObject(data.ToString()));
}
}
}
I am attempting to get a refresh token and use it to request a new access token when the temporary access token expires.
Spotify's documentation states the response body should contain the following json data:
{
"access_token": "NgCXRK...MzYjw",
"token_type": "Bearer",
"scope": "user-read-private user-read-email",
"expires_in": 3600,
"refresh_token": "NgAagA...Um_SHo"
}
However, using my code below only provides the following:
{
"access_token": "xxxx....",
"token_type": "Bearer",
"expires_in": 3600
}
I am using the following function to request an access token:
def get_access_token(client_id, client_secret): # getting access token from spotify using client ID
# Encoding Client ID and Client Secret in Base64
token_url = "https://accounts.spotify.com/api/token"
client_creds = f"{client_id}:{client_secret}"
client_creds_b64 = base64.b64encode(client_creds.encode())
token_data = {
"grant_type": "client_credentials"
}
token_headers = {
'Authorization': f"Basic {client_creds_b64.decode()}"
}
r = requests.post(token_url, data=token_data, headers=token_headers)
valid_request = r.status_code in range(200, 299)
token_response_data = r.json()
# pretty print response body
print(json.dumps(token_response_data, indent=2)) # response 200 -> successful attempt
if valid_request:
access_token = token_response_data['access_token']
return access_token
I am unsure why the scope and refresh token are missing from the response body. How can I alter this function to include these?
Thanks in advance for your time!
Spotify documentation: https://developer.spotify.com/documentation/general/guides/authorization/code-flow/
Altering the token data fixes this:
token_data = {
"grant_type": "authorization_code",
"code": "xxxx....",
"redirect_uri": "your redirect uri from Spotify for devs"
}
You need to set up a redirect uri on Spotify for devs, then encode it to use it as a parameter.
To get the 'code' parameter fill-out this URL with your data and you will be redirected to your redirect uri.
https://accounts.spotify.com/authorize?client_id=YOUR CLIENT ID&response_type=code&redirect_uri=YOUR ENCODED REDIRECT URI&scope=playlist-modify-public%20playlist-modify-private
The code will then be in the search bar to copy/paste. It should look something like this:
https://your redirectURI?code=xxx.....
Here is a good video guide for reference:
https://www.youtube.com/watch?v=-FsFT6OwE1A&ab_channel=EuanMorgan
So I'm trying to use python requests to make a PUT request to Azure (to create/update notification hub - https://learn.microsoft.com/en-us/rest/api/notificationhubs/notificationhubs/createorupdate#mpnscredential .
My code:
url = "https://management.azure.com/subscriptions/mysub/resourceGroups/Default-NotificationHubs-WestEurope/providers/Microsoft.NotificationHubs/namespaces/myNamespace/notificationHubs/notificationHubName?api-version=2016-03-01"
bearer_token = "my very long token"
headers = {
"dataType": "json",
"accept":"application/json",
"contentType":"application/json",
"Authorization": "Bearer " + bearer_token }
filepath = "/Users/..../pathTo.p12"
with open(filepath) as fh:
byte_array_p12 = fh.read()
data = {
'location': "West Europe",
'properties.apnsCredential': {
'properties.apnsCertificate': byte_array_p12,
'properties.certificateKey': "some nice pass"
}
}
r = requests.put(url, data, headers = headers)
But running r gives me 415 error.
r.text
u'{"error":{"code":"UnsupportedMediaType","message":"The content media type \'application/x-www-form-urlencoded\' is not supported. Only \'application/json\' is supported."}}'
Where did that \'application/x-www-form-urlencoded\' come from? I am explicitly setting headers for that request, and that one is not included... I am clueless.
I have tried the "Try" functionality on the afformentioned Azure page, where you can try constructing the body yourself, but it is buggy...
Thanks for any help!
The HTTP header should Content-Type and not contentType.
headers = {
"dataType": "json",
"accept":"application/json",
"Content-Type":"application/json",
"Authorization": "Bearer " + bearer_token }
Also, parameter data should be JSON encoded.
r = requests.put(url, json=data, headers=headers)
I am using Alamofire for the HTTP networking in my app. But in my api which is written in python have an header key for getting request, if there is a key then only give response. Now I want to use that header key in my iOS app with Alamofire, I am not getting it how to implement. Below is my code of normal without any key implementation:
Alamofire.request(.GET,"http://name/user_data/\(userName)#someURL.com").responseJSON { response in // 1
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result)
}
I have a key as "appkey" and value as a "test" in my api. If anyone can help. Thank you!
This should work
let headers = [
"appkey": "test"
]
Alamofire.request(.GET, "http://name/user_data/\(userName)#someURL.com", parameters: nil, encoding: .URL, headers: headers).responseJSON {
response in
//handle response
}
let headers: HTTPHeaders = [
"Accept": "application/json",
"appkey": "test"
]
Alamofire.request("http://name/user_data/\(userName)#someURL.com", headers: headers).responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result)
}