Simple JSON request with cURL to Mochiweb - json

I have a very simple 'hello world' Mochiweb server (I just started my introduction into it), which takes a JSON request and sends it back:
'POST' ->
case Path of
"dummy" ->
Data = Req:parse_post(),
Json = proplists:get_value("json", Data),
Struct = mochijson2:decode(Json),
Action_value = struct:get_value(<<"action">>, Struct),
Action = list_to_atom(binary_to_list(A)),
Result = [got_json_request, Action],
DataOut = mochijson2:encode(Result),
Req:ok({"application/json",[],[Result]});
The thing is that when I try to make a request to it with cURL it fails:
curl -i -H "Content-Type: application/json" -H "Accept: application/json" -X POST -d '{"action":"dummy"}' http://localhost:8080/dummy
The Mochiweb log is quite difficult to read, but as I understand the error happens at this line:
Json = proplists:get_value("json", Data)
I have put a couple of io:formats in the code and found out that both Data and Json variables are [] after I make a request with cURL.
On the other hand, when I do a very simple request with cURL:
curl -d '{"action":"dummy"}' http://localhost:8080/dummy
both Data and Json are [{"{\"action\":\"dummy\"}",[]}], but in that case the line Struct = mochijson2:decode(Json) fails.
For some strange reason Mochiweb does not see the JSON data in the POST request in case the header has the "application/json" value.
So, the question is: How do I make a correct POST request with JSON data to a Mochiweb server?
EDIT: Json variable has the undefined value.

Try something along the lines of
Data = Req:recv_body(),
Json = mochijson2:decode(Data),
...
You should at least ensure method post and the content type ahead of this.

This is not about POST nor get.
It's about how you post your data to send to your server
When you send a json data to server, you need to make it as key=value
curl -d "key=value" "http://your.domain.com/path"
Therefore, if you want to post json as '{"action":"dummy"}', for GET request
curl -d "json='{\"action\":\"dummy\"}'" http://localhost:8080/dummy
For POST request as a file,
curl -F "json=#filename.json" http://localhost:8080/dummy
of course, when you send as a file, you need to read the posted file from the server side.

Related

Jenkins : Extract data from Jira curl

I use a curl to get the status of a Jira issue :
result = sh(returnStdout: true, script: """curl -D- -k -u $JIRA_LOGIN:$JIRA_PWD -X GET -H "Content-Type: application/json" $url""")
This returns a String like :
{"expand":"renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations","id":"*****","self":"*****","key":"*****","fields":{"status":{"self":"*****","description":"Issues in development","iconUrl":"****","name":"DEVELOPMENT","id":"10400","statusCategory":{"self":"****","id":4,"key":"indeterminate","colorName":"yellow","name":"In Progress"}}}}
How I can extract the data "DEVELOPMENT" in this string ? I try to parse it in JSON but it's not working :
status_json = new JsonSlurper().parse(result)
with the error "java.io.NotSerializableException: groovy.json.JsonSlurper"
You can check out the JsonSlurper's documentation:
Jira holds all issue fields under the "fields" key in JSON. So, after you get the JSON, you just need to go to the fields.status.name in order to get "DEVELOPMENT" text.
Here's a simple approach:
def jsonSlurper = new JsonSlurper()
def issueObj = jsonSlurper.parseText('...') // Your Jira response will be here
issueObj.fields.status.name // It will give you the status' name.

Access Next Offset from GET http api request

I'm unable to understand pagination of Chargebee (https://apidocs.chargebee.com/docs/api) , I need to create a request in where I can add next offset to the request to get further data (without setting limit other then by default, which is 10). But i'm unable to understand how http request will be formed with this given next_offset like attached image.
Screenshot of request and response
I have had success submitting the identical request with the offset tacked onto the end. Here is an example:
First Request
curl -s https://xxyyzz.chargebee.com/api/v2/events -G -K /home/xxyyzz/.cb_curl_key.cfg --data-urlencode limit=2 --data-urlencode occurred_at[between]="[1554076800,1554077099]"
JSON results:
{
"list": [
{"event": {
"id": "ev_xxyyzz1",
"occurred_at": 1554077022,
...
"next_offset": "[\"1556428868000\",\"364450353\"]"
}
The tool I used to display the json is trying to be helpful with the backslashes.
The real next_offset value is
["1556428868000","364450353"]
Second Request
Identical to the first with
offset="["1554077017000","345017569"]"
tacked on to the end:
curl -s https://xxyyzz.chargebee.com/api/v2/events -G -K /home/xxyyzz/.cb_curl_key.cfg --data-urlencode limit=2 --data-urlencode --data-urlencode occurred_at[between]="[1554076800,1554077099]" offset="["1554077017000","345017569"]"
JSON results:
{
"list": [
{"event": {
"id": "ev_xxyyzz3",
"occurred_at": 1556429028,
}
Keep repeating the process until the "next_offset" key does not appear in the JSON result.

Error while Passing Json string in scala using Curl

I am trying to post a json string using curl in scala. My curl command works fine if executed from linux box but throes an error(("message": "Must provide query string.",) always from scala.
my working curl command in linux:
curl http://laptpad1811:5000/graphql -H "Content-Type: application/json"
-X POST -d '{"query":"mutation
CreateFileReceivedEvent($createFileReceivedEventInput:
CreateFleReceivedEventInput!) { createFileReceivedEvent(input:
$createFileReceivedEventInput) { clientMutationId }}","variables":
{"createFileReceivedEventInput":
{"clientMutationId":"Test","fileReceivedEvent":{"file":
{"fileTrackingId":"83a86c44-66a5-4de0-9b7f-
c6995877279d","name":"textfile_2017-08-21T15:58:45Z","fileType":
{"code":"textfile"}},"eventTimestamp":"2017-08-
21T15:59:30Z"}}},"operationName":"CreateFileReceivedEvent"}'
My scala code:
step1: copying the entire json string(pay load) to txt file
'{"query":"mutation CreateFileReceivedEvent($createFileReceivedEventInput:
CreateFleReceivedEventInput!) { createFileReceivedEvent(input:
$createFileReceivedEventInput) { clientMutationId }}","variables":
{"createFileReceivedEventInput":
{"clientMutationId":"Test","fileReceivedEvent":{"file":
{"fileTrackingId":"83a86c44-66a5-4de0-9b7f-
c6995877279d","name":"textfile_2017-08-21T15:58:45Z","fileType":
{"code":"textfile"}},"eventTimestamp":"2017-08-
21T15:59:30Z"}}},"operationName":"CreateFileReceivedEvent"}'
step2:
val data=fromFile("/usr/test/data.txt").getLines.mkString
step3:
val cmd = Seq("curl", "http://laptpad1811:5000/graphql", "-H",
"'Content-Type:application/json'" ,"-X", "POST", "-d" , data)
step4:
cmd.!!
I get the below error
String =
"{
"errors": [
{
"message": "Must provide query string.",
"stack": "BadRequestError: Must provide query string.\n
I have tried to change " to ' and mutiple combinations of the json string but I always get the same error.
I suspect that your issue is that sys.process doesn't pass commands through the shell (e.g. bash), so quotes that are necessary in the shell become unnecessary in Scala (and get passed through to the command which in the case of Unix-style utilities will probably result in unexpected behavior).
So try:
val cmd = Seq("curl", "http://laptpad1811:5000/graphql", "-H", "Content-Type: application/json", "-X", "POST", "-d", data)
Likewise remove the single quote wrapping from your text file.
I would however, counsel against spawning a curl in Scala and advise using one of the existing http client libraries (I personally like Gigahorse).

Making HTTP form POST request

I'm trying to make a HTTP form POST request to http://example.co.uk.
I used curl http://example.co.uk -d #example.json. However it gives me error saying it should only contain single field called application.
example.json file:
{"application":[
{
"name":"John",
"email":"john#example.com",
"github":"https://github.com/john",
"twitter":"https://twitter.com/john",
}
]
}
What's the correct way to do it? Any help will be appreciated. Thanks
You'll need to indicate to the server that the content type is JSON instead of the standard form-encoded data, so use:
curl -H "Content-Type: application/json" http://example.co.uk -d #example.json
Also, your JSON file should be valid JSON i.e. without any ending/redundant , characters, so:
{"application":[
{
"name":"John",
"email":"john#example.com",
"github":"https://github.com/john",
"twitter":"https://twitter.com/john"
}
]
}
Check the contents at http://jsonlint.com

Grails command object and 404 when space inside JSON from CURL

I have inherited a controller.
When a post request is made, with a well structured JSON document everything is fine.
When the JSON contains a space in a feld, 404 is returned.
However, when the same request is made from mozilla restclient extension everything works.
The CURL request specifically is:
curl --include \
--request POST \
--header "Content-Type: application/json" \
--header "Accept: application/json" \
--data-binary "{
"planCode" : "My Test App-standard"
}" \
"https://localhost/signupApi/v2/signup"
URLMapping:
"/signupApi/v2/$action"{
parseRequest = true // parse json, and assign to params
controller = "signupApiSignup"
}
So, why would a space in curl cause problems in the request body that grails receives?
Thanks
You are not quoting your strings there properly in your shell. Use ' for your parameters, if you plan to use "sensitive" chars like " there. Or use \" inside. Also curl can read a filename if you prefix it with # instead of the actual data.
Yet in this case maybe quoting with ' is easiest. E.g.:
...
--data-binary '{
"planCode" : "My Test App-standard"
}'
...