There is very limited documentation when it comes to the HTTP library in Julia Lang. Not just that, but there are no up to date Stack Overflow questions regarding the HTTP library in general.
With that said, how do you send POST requests using Julia + HTTP to a Django Restful API (DRF)?
Julia 1.7, 1.8
If you are sending json formatted data (simple Django POST request):
begin
using JSON
using HTTP
const url = "http://127.0.0.1:8000/api/profile"
payload = Dict("email" => "email#email.com", "password" => "12345password")
response = HTTP.request(
"POST", url, ["Content-Type" => "application/json"], JSON.json(payload))
# this is necessary, JULIA discontinued python style Dictionaries
response = JSON.parse(String(response.body))
println(response)
end
If you are sending header information like Authentication tokens, etc.
begin
using JSON
using HTTP
const url = "http://127.0.0.1:8000/api/profile"
payload = Dict("email" => "email#email.com", "password" => "12345password")
access_token = "some access token"
headers = Dict(
"Content-Type" => "application/json",
"Authorization" => "Bearer $access_token")
response = HTTP.request(
"POST", url, headers, JSON.json(payload))
# this is necessary, JULIA discontinued python style Dictionaries
response = JSON.parse(String(response.body))
println(response)
end
trying to send a POST to WCF services that accepts JSON string based on the website's JS. I had no luck buy just copy and paste the JSON string in an excel cell and use VBA's XMLHTTP60 to post. Always get bad data (status 400).
tried JSON string and JSON in cell doesn't work. I tried different JSON encoding doesn't seem to work either.
anyidea how I would post a JSON String to WCF?
My guess is somehow the VBA string loses its format during the request. Or different character code \ and : was send.
{"country":"{\"name\":\"USA\",\"population\":\"10000\"}\"}
{"country":"{"name":"USA","population":"10000"}"}
my VBA code
Sub test()
Dim XMLRequest As New MSXML2.XMLHTTP60
website = "URL"
postdata = thisworkbook.worksheets("Sheet1").range("A1").value
XMLRequest.Open "POST", "webSite", False
XMLRequest.SetRequestHeader "Content-Type", "application/json; charset=UTF-8"
XMLRequest.send postdata
end sub
However, I can use a browser console to send the AJAX with no problem.
var data=JSON.Stringify('{"country":"{"name":"USA","population":"10000"}"}');
$Ajax({
method: "POST",
URL: URL,
dataType:json,
contentType: "application/json; charset=UTF-8",
data:data,
cache: false
})
or I have no problem sending javascript in VBA via IE object
IE.Document.parentWindow.execScript "ajax call","javascript"
but my ultimate goal is to bypass IE, since it is not stable especially controlling through VBA.
In my controller file I have a method that reads the incoming HTTP request, reads the user data from the Database, encodes the result in JSON (using jsx) and sends it in response.
sensorusersdetails('GET', []) ->
Headers = [{'Access-Control-Allow-Origin', "*"},
{'Access-Control-Allow-Methods', "GET, OPTIONS"},
{'Content-Type', "application/json"},
{'Access-Control-Allow-Headers', "X-Requested-With"},
{'Access-Control-Max-Age', "180"}],
Building = Req:query_param("bld"),
io:format("User Data request from Node.js server~n~p~n",
[Req:query_params()]),
{{Year,Month,Day},{_,_,_}} = erlang:localtime(),
StrDate = lists:flatten(io_lib:format("~4..0w-~2..0w-~2..0w",
[Year,Month,Day])),
BUserDataList = boss_db:find(sensoruser_data, [{building, 'equals', Building}]),
io:format("Current Users Data stored in the database: ~n~p~n",[BUserDataList]),
MyUserJSONList = sensor_preapre_data(BUserDataList, StrDate),
io:format("The Present Date Sensor Users Data with Binary 1: ~n~p~n",[MyUserJSONList]),
MyUserJSONListLength = length(MyUserJSONList),
if MyUserJSONListLength > 0 ->
MyFinalList = sensor_data_final(MyUserJSONList),
io:format("The Present Date Sensor Users Data without Binary 2: ~n~p~n",[MyFinalList]),
{200, [MyFinalList], Headers};
%%{json, MyFinalList};
true ->
{200, "NO DATA FOUND", Headers}
%%{json, [{error, "NO DATA FOUND"}]}
end.
In the Chicagoboss Server logs I'm getting:
The Present Date Sensor Users Data with Binary 1:
[[<<"{\"username\":\"KPBatman1\",\"building\":\"A\",\"device\":\"Fitbit\",\"date\":\"2017-07-23\",\"calorie\":732,\"distance\":6.4399999999999995,\"elevation\":0,\"floor\":0,\"steps\":8}">>],
[<<"{\"username\":\"KPSuperman1\",\"building\":\"A\",\"device\":\"Jawbone\",\"date\":\"2017-07-23\",\"calorie\":0,\"distance\":0.0,\"elevation\":0,\"floor\":0,\"steps\":0}">>]]
The Present Date Sensor Users Data without Binary 2:
[["{\"username\":\"KPBatman1\",\"building\":\"A\",\"device\":\"Fitbit\",\"date\":\"2017-07-23\",\"calorie\":732,\"distance\":6.4399999999999995,\"elevation\":0,\"floor\":0,\"steps\":8}"],
["{\"username\":\"KPSuperman1\",\"building\":\"A\",\"device\":\"Jawbone\",\"date\":\"2017-07-23\",\"calorie\":0,\"distance\":0.0,\"elevation\":0,\"floor\":0,\"steps\":0}"]]
However, when I send the HTTP request - the JSON response I am getting:
{"username":"KPBatman1","building":"A","device":"Fitbit","date":"2017-07-23","calorie":732,"distance":6.4399999999999995,"elevation":0,"floor":0,"steps":8}
{"username":"KPSuperman1","building":"A","device":"Jawbone","date":"2017-07-23","calorie":0,"distance":0.0,"elevation":0,"floor":0,"steps":0}
What is the correct way to send JSON response?
However, when I send the HTTP request - the JSON response I am
getting:
{"username":"KPBatman1","building":"A", ...}
{"username":"KPSuperman1","building":"A", ...}
And? What did you expect/want to get?
The following code works for me because the output is what I expected to see:
-module(cb_tutorial_greeting_controller, [Req]).
-compile(export_all).
hello('GET', []) ->
Headers = [
{'Access-Control-Allow-Origin', "*"},
{'Access-Control-Allow-Methods', "GET, OPTIONS"},
{'Content-Type', "application/json"},
{'Access-Control-Allow-Headers', "X-Requested-With"},
{'Access-Control-Max-Age', "180"}
],
Data = [
[<<"{\"username\":\"KPBatman1\",\"building\":\"A\"}">>],
[<<"{\"username\":\"KPSuperman1\",\"building\":\"A\"}">>]
],
Json = jsx:encode(Data),
{200, Json, Headers}.
In my browser, I see:
[["{\"username\":\"KPBatman1\",\"building\":\"A\"}"],["{\"username\":\"KPSuperman1\",\"building\":\"A\"}"]]
Note that MyFinalList isn't even valid JSON:
13> Data = [["{\"a\":\"Batman\"}"], ["{\"b\":\"Superman\"}"]].
[["{\"a\":\"Batman\"}"],["{\"b\":\"Superman\"}"]]
14> jsx:is_json(Data).
false
See what I did there?
What I want is a POST request in kemal where the body has a certain number of keys/values that I want to access and then an arbitrary JSON Object that I just want to stringify and pass on and later parse back to JSON.
My problem is that I apparently can't get the types right.
Think of a potential JSON body like this:
{
"endpoint": "http://example.com",
"interval": 500,
"payload": {
"something": "else",
"more": {
"embedded": 1
}
}
}
Now what I've been trying to do is the following:
require "kemal"
post "/schedule" do |env|
endpoint = env.params.json["endpoint"].as(String)
interval = env.params.json["interval"].as(Int64)
payload = String.from_json(env.params.json["payload"].as(JSON::Any))
# ... move things along
env.response.content_type = "application/json"
{ id: id }.to_json
end
Kemal.run
Now apparently what I seem to be getting when accessing "payload" is something of type Hash(String, JSON::Type), which confuses me a bit.
Any ideas how I'd be able to just get a sub-JSON from the request body, transform it to String and back to JSON?
Updated: payload is a type of JSON::Type. Casting and then calling .to_json does the trick.
require "kemal"
post "/schedule" do |env|
endpoint = env.params.json["endpoint"].as(String)
interval = env.params.json["interval"].as(Int64)
payload = env.params.json["payload"].as(JSON::Type)
env.response.content_type = "application/json"
payload.to_json
end
Kemal.run
I'm using Google Chrome REST API to get information from my web server.
I use: Content-Type = "application/json"
and a Post command that includes groovy code inside the Payload (the header remains empty):
{
"aaa": "dan",
"bbb": "my_data",
"ccc": "my_type"
}
or sometimes the Post is empty also in the Payload
This works just fine (I'm getting the response in json format)
I want to post this command with VBA from excel so the response would get into a VBA variable, which I can then print into some cell in the worksheet. How do I do it?
Do I need to download some library for that?
I tried (without success):
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
URL = "[my_URL]"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "Content-type", "application/json"
Worksheets("sheet1").Cells(1, 1)=objHTTP
Please advise,
Needed to add:
objHTTP.setTimeouts 30000, 60000, 30000, 120000