I am making a post request from django to nodejs
v = {}
v['id'] = 'test'
y=requests.post('http://localhost:3000',params=v)
How can I parse this data in nodejs? Below is my code, but it shows undefined.
app.post('/', function (req, res) {
console.log(req.body.id) //this shows Cannot read property 'id' of undefined
res.send('hello')
})
note that with python-requets the POST verb expects a dictionary as data
v = {}
v['id'] = 'test'
y=requests.post('http://localhost:3000',data=v)
params is generally used by the get verb. Having said that I am not sure why you want to connect django and node in this way. Wouldn't it be easier to write the entire thing in one or the other?
Have you enabled the body parser?
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
Related
Trying to create feed document (here ) and I'm getting InvalidInput error code.
Authentication works well (I tried other endpoints and it works) so I think headers are not the issue.
Here is my sample code:
endpoint = 'https://sellingpartnerapi-eu.amazon.com/feeds/2020-09-04/documents'
body = {
"contentType": "text/tab-separated-values; charset=UTF-8"
}
resp = requests.post(
endpoint,
auth=self.amazon_auth.auth,
headers=self.amazon_auth.headers,
json=body
)
return resp
Response code:
{'errors': [{'code': 'InvalidInput',
'message': 'Invalid Input',
'details': ''}]}
I was also trying to use different contentType and charset (like text/plain) but I receive same error code!
This is first step of Submit feed tutorial.
I'm trying to create feed so I can get cartonIds to download labels for a shipment I created over Amazon Seller Central.
Any hint, help is more than welcome!
Thanks!
I solved this issue by:
requests.post(data=json.dumps(body))
Also make sure you pass the body for signing as well
I use RestSharp
restRequest1.AddParameter(....); gave me the same error as yours Invalid Input
but the below line gave me a response value
restRequest1.AddJsonBody(new { contentType = "text/xml; charset=UTF-8" });
It serializes obj to json format and adds it to the request body.
This code snippet in C# worked for me, i successfully uploaded a feed
My upload method:
private static bool UploadFile(byte[] encrypted, string url)
{
bool isUploaded = false;
var contentType = "text/tab-separated-values; charset=UTF-8";
var parameter = new Parameter
{
Name = contentType,
Value = encrypted,
Type = ParameterType.RequestBody
};
var restRequest = new RestRequest(Method.PUT);
restRequest.Parameters.Add(parameter);
var restClient = new RestClient(url);
var response = restClient.Execute(restRequest);
isUploaded = response.StatusCode == System.Net.HttpStatusCode.OK;
return isUploaded;
}
TL,DR; How should HTTP PATCH communicate the removal of resource attributes when using a FieldMask?
Google's API Design Guide for implementing standard methods states that a partial update should be achieved using a FieldMask. Below is my own contrived example to update a Test resource:
The API of the service defines a Test resource and an HTTP PATCH method (UpdateTest) for partial updates.
// A test resource.
message Test {
string name = 1;
google.protobuf.StringValue description = 2;
}
// Request message for update method.
message UpdateTestRequest {
// The resource name of the test to be updated.
string name = 1;
// Wrap the actual data in a data field.
Test test = 2;
// Field mask to support partial updates.
google.protobuf.FieldMask update_mask = 3;
}
// Partially update a Test resource.
rpc UpdateTest(UpdateTestRequest) returns (google.protobuf.Empty) {
option (google.api.http) = {
patch: "v1/{name=tests/*}"
body: "*"
};
}
An equally contrived server implementation uses the FieldMask to merge the resources (proto messages):
updated_test = v1_test_pb2.Test(name = 'Updated')
original_test = v1_test_pb2.Test(
name = 'Original',
description = google.protobuf.wrappers_pb2.StringValue(
value = 'I am Original!')
)
mask = google.protobuf.field_mask_pb2.FieldMask(
paths = ['name', 'description']
)
# from, to
mask.MergeMessage(updated_test, original_test)
print(updated_test)
The end result is a patch Test resource:
name: "Updated"
description {
value: "I am Original!"
}
Clearing the description field removes the property altogether:
updated_test = v1_test_pb2.Test(name = 'Updated')
updated_test.ClearField('description')
original_test = v1_test_pb2.Test(
name = 'Original',
description = google.protobuf.wrappers_pb2.StringValue(
value = 'I am Original!')
)
# from, to
mask.MergeMessage(updated_test, original_test)
print(updated_test)
...the final patched Test resource would be:
name: "Updated"
Great. But how would this be encoded in the HTTP PATCH request?
The only "solution" I can think of is that, if the FieldMask contains description but the updated Test resource doesn't provide a value, it should be removed using ClearField.
This would require manually visiting each field either in the mask, or the Test messaage (or both) to determine whether the it should be removed. This seems crazy, especially if a resource has many fields.
I am learning how web apps work and after successfully creating connection between front and back end I managed to perform get request with axiom:
Route in my Flask
#app.route('/api/random')
def random_number():
k = kokos()
print(k)
response = {'randomNumber': k}
return jsonify(response)
my kokos() function
def kokos():
return (890)
Function that I call to get data from backend:
getRandomFromBackend () {
const path = `http://localhost:5000/api/random`
axios.get(path)
.then(response => {this.randomNumber = response.data.randomNumber})
.catch(error => {
console.log(error)
})
}
Now suppose I have an input field in my App with value that I want to use in the function kokos() to affect the result and what is going to be displayed in my app.. Can someone explain me how to do that?
Is this what POST requests are for and I have to post first and then get? Or can I use still GET and somehow pass "arguments"? Is this even GET and POST are for or am I making it too complicated for myself?
Is this the proper way to do these kind of thing? I just have a lot of code in python already written and want to simply exchange data between server and client.
Thank you, Jakub
You can add second argument
axios.get(path, {
params: {
id: 122
}
})
.then ...
You can pass id like this or anything it will be available in get params at python side like we pass in URL.
python side [Flask] (http://flask.pocoo.org/docs/1.0/quickstart/#accessing-request-data)
To access parameters submitted in the URL (?key=value) you can use the args attribute:
def random_number():
id = request.args.get('id', '')
k = kokos(id)
id will be passed kokos function if no id is provided it will be blank ''
you can read axios docu to make complex requests.
https://github.com/axios/axios
if any doubt please comment.
I am trying to upload an image to Etsy through the API. However, the example on their website is given in PHP which I don't know how to code. I only know how to work with Python. On their website it says:
Image uploads can be performed using a POST request with the Content-Type: multipart/form-dataheader, following RFC1867.
Their example which is in PHP
// You must define the constants OAUTH_CONSUMER_KEY and OAUTH_CONSUMER_SECRET
// You must also assign values to the variables $access_token, $access_token_secret,
// $listing_id and $filename, and $mimetype.
// Your image file is assumed to be in the same directory as this code.
$oauth = new OAuth(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET);
$oauth->enableDebug();
$oauth->setToken($access_token, $access_token_secret);
try {
$source_file = dirname(realpath(__FILE__)) ."/$filename";
$url = "https://openapi.etsy.com/v2/listings/".$listing_id."/images";
$params = array('#image' => '#'.$source_file.';type='.$mimetype);
$oauth->fetch($url, $params, OAUTH_HTTP_METHOD_POST);
$json = $oauth->getLastResponse();
print_r(json_decode($json, true));
} catch (OAuthException $e) {
// You may want to recover gracefully here...
print $oauth->getLastResponse()."\n";
print_r($oauth->debugInfo);
die($e->getMessage());
}
In API doc it says
HTTP Method = POST
URI = /listings/:listing_id/images
This is what I have so far in Python:
client_secret=client_secret,resource_owner_key=resource_owner_key,resource_owner_secret=resource_owner_secret)
url = 'https://openapi.etsy.com/v2/listings'
payload = {'listing_id':'2343432434', 'images': :('test1.jpg', open('test1.jpg', 'rb'), 'image/jpeg')}
result = etsy.post(uri, params=payload)
When I run this code I get an 403 error. How can I fix my code so that it functions correctly? I have looked at other examples and just can't seem to make it work.
How to use python as a backend for an Android App that is built using C#? The Python Backend is written using the Flask framework. The Android app is built using xamarin.
No matter what type of technology your server or the client use if they can communicate with each other using some sort of standard "protocol".
There are many ways to communicate both sides (client and server) like sockets, xml, json, etc. They just need to understand each other.
In your particular case I suggest to build a REST or RESTful API (https://flask-restful.readthedocs.org/en/0.3.3/) on the server and a REST client library on the client.
There are many ways and libraries to call REST APIs from C#:
The built-in method would be using HttpWebRequest as you can see on this link:
private async Task<JsonValue> FetchWeatherAsync (string url)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (new Uri (url));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync ())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream ())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run (() => JsonObject.Load (stream));
Console.Out.WriteLine("Response: {0}", jsonDoc.ToString ());
// Return the JSON document:
return jsonDoc;
}
}
}
But I don´t recommend it if you don´t want your app to be full of crap (boiler plate code) everywhere.
A helper library could be, for example, RESTSharp. It allows you to build REST calls easily and cast the response to your typed objects. Here´s and example:
var client = new RestClient("http://example.com");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("resource/{id}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("id", "123"); // replaces matching token in request.Resource
// easily add HTTP Headers
request.AddHeader("header", "value");
// add files to upload (works with compatible verbs)
request.AddFile(path);
// execute the request
RestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
// or automatically deserialize result
// return content type is sniffed but can be explicitly set via RestClient.AddHandler();
RestResponse<Person> response2 = client.Execute<Person>(request);
var name = response2.Data.Name;
// easy async support
client.ExecuteAsync(request, response => {
Console.WriteLine(response.Content);
});
// async with deserialization
var asyncHandle = client.ExecuteAsync<Person>(request, response => {
Console.WriteLine(response.Data.Name);
});
// abort the request on demand
asyncHandle.Abort();
You can search "C# REST client" on google and judge by yourself. But IMHO, the easier and nicer to code REST client I´ve ever used is Refit.
Why? you define API calls and responses with just an interface. No coding required at all! Even more, all your API calls will be async by default, something needed for mobile apps to be responsive. From the author´s readme:
public interface IGitHubApi
{
[Get("/users/{user}")]
Task<User> GetUser(string user);
}
var gitHubApi = RestService.For<IGitHubApi>("https://api.github.com");
var octocat = await gitHubApi.GetUser("octocat");
I´ve used this library on Xamarin Android/iOS projects and it works well. No issues at all.
Hope it helps