requests post from django to nodejs - python

I trying to send data from django to nodejs. I receive but can't read data params.
Django:
response = {
"status": "success",
"voto": all_votes,
"user_choice": new_vote.value if new_vote else None
}
import requests
requests.post('http://localhost:8081/vote_added', data = response)
NodeJS:
//router/index
router.post('/vote_added', votes.vote_added);
//votes controller
module.exports.vote_added = function(req, res) {
console.log("test", req.params)
console.log("test2", req.body)
console.log("test3", req.query)
}
ps: my response is a dict

I fix that. Just change data to params in django request:
requests.post('http://localhost:8081/vote_added', data = response)
to
requests.post('http://localhost:8081/vote_added', params = response)
and in nodejs, work with req.query

Related

Python requests post reponse 400

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()));
}
}
}

POST request payload in python not reaching PHP server

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.

Trying to post data to firestore using requests

im trying to post JSON data to firestore using requests and it keeps returning this error.
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name \"{\"data\": \"message\"}\": Cannot bind query parameter. Field '{\"data\": \"message\"}' could not be found in request message.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"description": "Invalid JSON payload received. Unknown name \"{\"data\": \"message\"}\": Cannot bind query parameter. Field '{\"data\": \"message\"}' could not be found in request message."
}
]
}
]
}
}
I've tried different method using different types of JSON Encoding and still returns the same error. i would appreciate if someone could look into this for me. Below is my code
def thestream(self, instance):
app = App.get_running_app()
s = requests.Session()
self.data = {u'data': u'message'}
self.headers = {"authorization": "bearer " + app.idToken}
r = s.post("https://firestore.googleapis.com/v1/projects/*******************************/databases/(default)/documents/messages/TemitayoAdefemi", params=json.dumps(self.data), headers=self.headers)
print(r.ok)
print(r.content.decode())
Try defining a Document resource in your payload:
self.data = {u'fields': {u'data': {u"stringValue": u'message'}}}
In your POST request, try passing the payload in data=self.data instead of param:
r = s.post("https://firestore.googleapis.com/v1/projects/***/databases/(default)/documents/messages/TemitayoAdefemi", data=self.data, headers=self.headers)

How to send rest API (Google Vision's API) request with python?

I guess my question is relatively simple and naive, but I'm new to use REST APIs so I would be grateful for any help or hint.
I'm trying to send a request with urllib (or another Python's library that I no need to install).
Based on their guide, The format is:
POST https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY
and the JSON request format is:
{
"requests":[
{
"image":{
"content":"/9j/7QBEUGhvdG9...image contents...eYxxxzj/Coa6Bax//Z"
},
"features":[
{
"type":"LABEL_DETECTION",
"maxResults":1
}
]
}
]
}
When I try to send the following text (just for test) in the URL line in my browser:
https://vision.googleapis.com/v1/images:{
"requests":[
{
"image":{
"content":"/9j/7QBEUGhvdG9eYxxxzj/Coa6Bax//Z"
},
"features":[
{
"type":"LABEL_DETECTION",
"maxResults":1
}
]
}
]
}?key=my_api_key
I get unfortunately a 404 error.
What should I do? Should I use any library in order to generate the request? Or should I to place the JSON request in another place in the URL?
If you need to send Request Body with the URL you can use CURL. To test REST API's there is a famous software called POSTMAN. By using this you can send requests and receive the response.
CURL,
curl -v -H "Content-Type: application/json" -X POST \
-d '{"image":{"content":"/9j/7QBEUGhvdG9...image contents...eYxxxzj/Coa6Bax//Z"}, "features":[{"type":"LABEL_DETECTION","maxResults":1}]}' https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY
Using POSTMAN you can give these values to it and get results.
Give URL,
https://vision.googleapis.com/v1/images:annotate?key=YOUR_API_KEY
Choose HTTP METHOD as,
POST
And add the REQUEST BODY under the raw field and choose JSON(application/json),
{
"requests":[
{
"image":{
"content":"/9j/7QBEUGhvdG9...image contents...eYxxxzj/Coa6Bax//Z"
},
"features":[
{
"type":"LABEL_DETECTION",
"maxResults":1
}
]
}
]
}
This works for me:
import base64
import requests
import json
URL = "https://vision.googleapis.com/v1/images:annotate?key=YOUR_TOKEN"
#image to base64, which is a long long text
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read())
#make api call
def image_request(image_path):
data = {
"requests":[
{
"image":{
"content":encode_image(image_path)
},
"features":[
{
"type":"LABEL_DETECTION", #other options: LABEL_DETECTION FACE_DETECTION LOGO_DETECTION CROP_HINTS WEB_DETECTION
"maxResults": 10
}
]
}
]
}
r = requests.post(URL, json = data)
return r.text
#arg = path of image
def main(argv):
api_answer = json.loads(image_request(argv[1]))
try:
rows = api_answer['responses'][0]['labelAnnotations']
except:
print(file_to_proccess)
print(api_answer)
data = []
for item in rows:
data.append([item['mid'], item['description'], item['score'], item['topicality']])
# save somewhere the data list...
if __name__ == "__main__":
main(sys.argv)
this was tested and work perfect
import base64
import requests
import json
url = "https://vision.googleapis.com/v1/images:annotate"
querystring = {"key":".........."}
headers = {
'Content-Type': "application/json",
}
def encode_image(image_path):
with open(image_path, "rb") as image_file:
return base64.b64encode(image_file.read())
def image_request(image_path):
payload = '{ \"requests\":[ { \"image\":{ \"content\":\"'+encode_image(image_path).decode('utf-8')+'" }, \"features\":[ { \"type\":\"TEXT_DETECTION\" } ] } ]}'
response = requests.request("POST", url, data=payload, headers=headers, params=querystring)
return response.text

How to use header key from the api to authenticate URL in iOS Swift?

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

Categories

Resources