Send a post request on PostMan - json

I have the following method I want to test using PostMan
public returnType name( String var1, String var2,String var3, String var4);
I tried to send a post request to test I sent one like this but it does not work:
{
"var1": "GU4777",
"var2" : "HU 888",
"var3" : "NU 8890",
"var4" : "UJ 9909"
}
I get this error:
I get this error: 10:11:16.588 [http-nio-8080-exec-3] WARN org.apache.cxf.jaxrs.impl.WebApplicationExceptionMapper - javax.ws.rs.InternalServerErrorException: HTTP 500 Internal Server Error
Can you guys please tell me the exact syntax I can use?
Thank you in advance;

Rest API
In order to do what you want to do you first need a HTTP server that listens for requests on a certain endpoint let's call that endpoint /test.
The server then must parse the JSON request body when it receives the request, extract the parameters and can then call the method name() using those parameters.
Here an implementation of a server like this using JavaScript and express.js. You do not need a library for a simple server like that (but I have used one here by reason of simplicity) and you can implement the server in pretty much any language you like e.g. Java.
While the syntax will differ in another language the idea will be the same.
import express from "express";
// create app
var app = express();
// middleware to parse json
app.use(express.json())
// listen for requests on the /test endpoint which you will hit with Postman
app.post("/test", function (req, res) {
// extract variables from json body
const var1 = req.body.var1;
const var2 = req.body.var2;
const var3 = req.body.var3;
const var4 = req.body.var4;
// call method
name(var1, var2, var3, var4);
// send response with HTTP code 200
res.status(200).send({
"message": `Executed name() with var1 = ${var1}, var2 = ${var2}, var3 = ${var3}, var4 = ${var4}`
});
});
// the function that you want to call on the server
function name(var1, var2, var3, var4){
console.log(var1, var2, var3, var4);
}
// start HTTP server and listen for requests on port 3000
const port = 3000;
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
You then need to start your server. In this case you do that by executing node server.js and then you can send requests to the server using Postman.
First, put your JSON payload (= the JSON from your question) into the request body and hit the localhost:3000/test route with a POST request. You should then receive a response with status code 200.
On the server side you can observe this:
RPC/ gRPC
In order to "directly" invoke a function on a server you might wanna have a look at RPC or gRPC for your preferred language.

I decided to use request path wish solved the issue.

Related

ESP32 gives error on HTTP Post to Flask server

My goal is to post data to a Flask server. For this I have the following code running on a computer(Jupyter):
from flask import Flask
from flask import request
app = Flask(__name__)
#app.route('/postjson', methods = ['POST'])
def postJsonHandler():
print (request.is_json)
content = request.get_json()
print (content)
return 'JSON posted'
app.run(host='0.0.0.0', port= 8090)
On the esp I have the following function responsible for posting, Right now it is just for testing , I will further the functionality later on.
//Posts data to server
void post_to_server(String url)
{
HTTPClient http;
// Prepare JSON document
JsonObject root = doc.to<JsonObject>();
JsonArray pressure = root.createNestedArray("pressure");
JsonArray time = root.createNestedArray("time");
pressure.add("Pressure");
time.add("Time");
// Serialize JSON document
String json;
serializeJson(root, json);
// Send request
http.begin(url);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(json); //Send the actual POST request
// Read response
Serial.print(http.getString());
if (httpResponseCode > 0)
{
String response = http.getString(); //Get the response to the request
Serial.println(httpResponseCode); //Print return code
Serial.println(response); //Print request answer
}
else
{
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
// Disconnect
http.end();
}
}
So here is the odd thing, when I call the function on a test server like this:
post_to_server("http://jsonplaceholder.typicode.com/posts");
It works and I get the following response on the Serial Monitor as expected:
{
"pressure": [
"Pressure"
],
"time": [
"Time"
],
"id": 101
But when I try to post to the Server running on my PC like this:
post_to_server("http://127.0.0.1:8090/postjson");
I get the following error:
0
[E][WiFiClient.cpp:258] connect(): socket error on fd 54, errno: 104, "Connection reset by peer"
Error on sending POST: -1
I cant really make sense of this so I came here. I would appriciate any help. I also get the following when I test on Postman:
post_to_server("http://127.0.0.1:8090/postjson");
This will never work on your ESP32.
127.0.0.1 is the "loopback address" - the same as the name localhost. It's shorthand meaning "this computer".
When you use this with a program you run on your Windows machine, the program will attempt to connect to the Windows machine.
When you use this with your ESP32, it means connection to the ESP32.
You need to use the IP address associated with your Windows machine's network connection, whether ethernet or WiFi. 127.0.0.1 will not work.

Unable to access data inside a string (i.e. [ object Object ]) that was originally sent as a JSON object

I'm using axios to send a JSON object as a parameter to my api. Before it post request is fired, my data starts of as a JSON object. On the server side, when I console.log(req.params) the data is returned as such
[object Object]
When I used typeof, it returned a string. So then I went to use JSON.parse(). However, when I used that, it returned an error as such
SyntaxError: Unexpected token o in JSON at position 1
I looked for solutions, but nothing I tried seemed to work. Now I'm thinking I'm sending the data to the server incorrectly.
Here's my post request using axios:
createMedia: async function(mediaData) {
console.log("SAVING MEDIA OBJECT");
console.log(typeof mediaData)
let json = await axios.post(`http://localhost:3001/api/media/new/${mediaData}`)
return json;
}
Any thoughts on how I can solve this?
You need to update your code using axios to provide the mediaData in the body of the request instead of the URL:
createMedia: async function(mediaData) {
console.log("SAVING MEDIA OBJECT");
console.log(typeof mediaData)
let json = await axios.post(`http://localhost:3001/api/media/new/`, mediaData)
return json;
}
In the backend (assuming you're using express here), you need to configure your application to use bodyParser:
var express = require('express')
, app = express.createServer();
app.use(express.bodyParser());
And then in your controller update your console.log(req.params) to console.log(req.body); then restart your node server

Express POST response-object not being updated when request parameter is changed

I am trying to make a tool to view our projects configuration JSON file. The config is generated based on what process.env variables are set. I've created an express server with one route that listens for the environment variables and returns the corresponding JSON configuration. However this only works on the first request, the correct process.env variables are being changed, but the JSON config being returned only reflects the first request made. Below is the POST route - the fpconf object should change to reflect the request parameters being sent. Is there some something I'm missing?
app.post( '/json', function ( req, res, next ) {
res.header( "Access-Control-Allow-Origin", "*" );
res.header( "Access-Control-Allow-Headers", "Origin, X-Requested- With, Content-Type, Accept" );
console.log( req.body );
_.merge( process.env, req.body );// Sets environment variables grabbed from post request
console.log( process.env ); // Log to ensure environment variables have been changed.
var fpUtils = appRootPath.require( '/libs/helpers/fputils' ),
fpconf = appRootPath.require( '/libs/fp-conf' );///file that returns the configuration JSON
console.log( "instance is " + process.env.NODE_APP_INSTANCE + ", deployment is " + process.env.NODE_ENV )
console.log(fpconf.data);
res.send( fpconf.data );
});

Node.js Express REST API - accessing JSON url params with GET request

I have a REST endpoint that is /geo/search and requires a number of long/lat coordinates to be sent as part of the request (GEO polygon).
Is there any way I can use JSON in the GET request? I was thinking that that URL encoding may be a solution:
var data = encodeURIComponent({"coordinates":[[-122.610168,37.598167],[-122.288818,37.598167],[-122.288818,37.845833],[-122.610168,37.845833],[-122.610168,37.598167]]});
How would I access these params in the route?
Answer to #1 - thanks to #mccannf
Using JQuery.param:
Client:
var test = {"coordinates":[[-122.610168,37.598167],[-122.288818,37.598167],[-122.288818,37.845833],[-122.610168,37.845833],[-122.610168,37.598167]]};
console.log($.param( test ));
Outputs:
coordinates%5B0%5D%5B%5D=-122.610168&coordinates%5B0%5D%5B%5D=37.598167&coordinates%5B1%5D%5B%5D=-122.288818&coordinates%5B1%5D%5B%5D=37.598167&coordinates%5B2%5D%5B%5D=-122.288818&coordinates%5B2%5D%5B%5D=37.845833&coordinates%5B3%5D%5B%5D=-122.610168&coordinates%5B3%5D%5B%5D=37.845833&coordinates%5B4%5D%5B%5D=-122.610168&coordinates%5B4%5D%5B%5D=37.598167
Answer to #2 - thanks to #Brad:
Server - Express route:
router.get('/search_polygon', function(req, res) {
console.log('Server received: ' + JSON.stringify(req.query.coordinates));
...
Outputs:
Server received: [["-122.610168","37.598167"],["-122.288818","37.598167"],["-122.288818","37.845833"],["-122.610168","37.845833"],["-122.610168","37.598167"]]
My issue was trying to pass these as part of the path, and not as parameters as they should be.

mocha - send json to post express route

I'm trying to send some json data to my '/sign_up' route in mocha test.
request = require 'supertest'
express = require 'express'
app = express()
Authentication = require("#{specDir}/../apps/authentication/routes")
authenticate = new Authentication app
Factory = require "#{specDir}/factories/user"
user = Factory.build 'user'
it 'creates an account', (done) ->
request(app).post('/sign_up').set('Accept', 'application/json').send(user).end (err, res) ->
expect(res.statusCode).to.equal 200
done()
However req.body in the callback function is undefined. Below I've shown a snippet of my route callback
#app.post '/sign_up', (req, res) ->
res.format
html: -> res.status(406).send 'invalid Content-Type'
json: ->
console.log req.body
res.status(200).send status: 'ok'
Probably I'm missing some small detail, but can't see what.. any ideas?
P.S. I'm well aware of that the tests pass and it does what it should, but before I move on to write more tests I gotta know how to send some data.
You're missing a body parser, add app.use(express.json()) in your code somewhere.