-2

i have the below posted json response.as shown below in json section, the parametersobject is emitted in this line (this is an angular application)

    this._FromInsToSiteDataService.emitOnSubmitButtonClikedBroadcast(parameters)

and it is received in

this.subscriptionBroadcastEmitterOnSubmitButtonClicked = this._FromInsecticidesToSiteMapDataService.getBroascastEmitterOnSubmitButtonClicked().subscribe((response:Object)=>{
        response['siteGeometry'] = this.selectedSite.geometry
        console.log("response: ", response)
        this.sSProvider.startWebServiceFor(response)
    });
    

in the latter code i want to pass the response which is in json format to the webservice and receive it as show in the websrvicepostedbelow`

when i run the code, i expected to see the contents of the json object which is

{
  "dist1": d1,
  "dist2": d2,
  "date1": date1,
  "date2": date2,
  "ingredient": activeIngredient
}

but i get NONE

please let me know how can i correctly get a json object from a webservice

json

 private submit() {
  let parameters = {
  "dist1": d1,
  "dist2": d2,
  "date1": date1,
  "date2": date2,
  "ingredient": activeIngredient
}
    
this._FromInsToSiteDataService.emitOnSubmitButtonClikedBroadcast(parameters)

receiving the json object

this.subscriptionBroadcastEmitterOnSubmitButtonClicked = this._FromInsecticidesToSiteMapDataService.getBroascastEmitterOnSubmitButtonClicked().subscribe((response:Object)=>{
        response['siteGeometry'] = this.selectedSite.geometry
        console.log("response: ", response)
        this.sSProvider.startWebServiceFor(response)
    });
    

webservice:

@app.route("/insSpecifications/<parameters>", methods=['GET'] )
def insSpecifications(parameters):
    # print(request.json())
    print(request.get_json())//returns NONE

    return "OK"
shoaib30
  • 877
  • 11
  • 24
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • @Chillie the this.sSProvider.startWebServiceFor(response) starts the webservice – Amrmsmb Aug 02 '21 at 07:26
  • You may want to modify your tags with appropriate ones to get the correct people to look at the question, as this question is lesser a flask, python question and more of JS – shoaib30 Aug 02 '21 at 07:31
  • Have you tested the Flask route from postman and did it print the json? Note that if you don't set the `content-type` to `application/json` in the header, `get_json()` returns null and also you are making a GET request, `get_json()` reads the body of a `post` or `put` request – shoaib30 Aug 02 '21 at 07:32
  • @shoaib30 would you please provide an example in code?how can i set the content-type?? – Amrmsmb Aug 02 '21 at 07:34
  • I will drop it as an answer – shoaib30 Aug 02 '21 at 07:38
  • @shoaib30 ok..fine – Amrmsmb Aug 02 '21 at 07:41

1 Answers1

0

Intro There are two parts to your question -

  1. Making a request from JS
  2. Creating a Flask API to handle the request

Both these have extensively answered on SO hence I will only summarize it here, please follow the links for more information

Answer

REST Method: When sending JSON data from the front end to the backend, you need to make a POST request or PUT depending on the need. Please read up on REST API concepts to understand the methods and purposes. https://www.w3schools.in/restful-web-services/rest-methods/

Making a request Depending on which library you use in the front end, the request might look different, but essentially you need to send a request with JSON in the body and HEADERS set appropriately i.e. Content-Type: application/json

Using FETCH this can be achieved by (auto-generated from postman)

var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");

var raw = JSON.stringify({
  "username": "Sample1",
  "email": "test2@test.com"
});

var requestOptions = {
  method: 'POST',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("localhost:5000/sample", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

But most libraries would have wrappers around this, please look into making a POST request for your respective JS library

Creating Flask API Finally, you need a Flask API to consume this request. Assuming it's a POST request. You need to create a route with method as POST and get the JSON data using get_json() : https://stackoverflow.com/a/20001283/5236575

So once the HEADERS are correctly set and a post request is made, your code should work fine by changing GET to POST

Note: The parameters field is captured correctly hence I'm leaving it as is, but that is not where your JSON body comes from

@app.route("/insSpecifications/<parameters>", methods=['POST'] )
def insSpecifications(parameters):
    # print(request.json())
    print(request.get_json())
    return "OK"

Testing You can test your API using Postman or any other API testing tool to see how the API behaves and validate if the issue you have is in the API or in the front-end code.

shoaib30
  • 877
  • 11
  • 24
  • i changed the GET method to POST and i get the following: INFO:werkzeug: - - [02/Aug/2021 10:05:50] "OPTIONS /insecticidesSpecifications/[object%20Object] HTTP/1.1" 200 - INFO:werkzeug: - - [02/Aug/2021 10:05:50] "GET /insecticidesSpecifications/[object%20Object] HTTP/1.1" 405 - – Amrmsmb Aug 02 '21 at 08:07
  • what is [object%20Object]?? – Amrmsmb Aug 02 '21 at 08:07
  • You are passing the JSON object from the JS code as an object in the URL, Hence you see `[object: Object]` as the URL param. You need to send the JSON in the body of the request not in the URL – shoaib30 Aug 02 '21 at 09:16
  • i am sending from angular not from js. please let me know how to access [object object] – Amrmsmb Aug 02 '21 at 09:20
  • Angular at the end of the day is JS running on the browser. Please look into how to make POST Request from angular - https://stackoverflow.com/a/61742826/5236575 – shoaib30 Aug 02 '21 at 09:26
  • accessing `[object Object]` isn't the problem you need to solve. If you send it correctly it wont come as '[`object Object]` – shoaib30 Aug 02 '21 at 09:27