I am new with Erlang and my doubt is how to create a JSON Object in Erlang and pass that object in REST API call. I have read so many posts but didn't get any satisfying answer.
Edit
Here I am calling the API:
offline_message(From, To, #message{type = Type, body = Body}) ->
Type = xml:get_text(Type),
Body = xml:get_text(Body),
Token = gen_mod:get_module_opt(To#jid.lserver, ?MODULE, auth_token, fun(S) -> iolist_to_binary(S) end, list_to_binary("")),
PostUrl = gen_mod:get_module_opt(To#jid.lserver, ?MODULE, post_url, fun(S) -> iolist_to_binary(S) end, list_to_binary("")),
to = To#jid.luser
from = From#jid.luser
if
(Type == <<"chat">>) and (Body /= <<"">>) ->
Sep = "&",
Post = {
"token":binary_to_list(Token),
"from":binary_to_list(from),
"to":binary_to_list(to),
"body":binary_to_list(Body)
},
?INFO_MSG("Sending post request to ~s with body \"~s\"", [PostUrl, Post]),
httpc:request(post, {binary_to_list(PostUrl), [], "application/json", binary_to_list(Post)},[],[]),
ok;
true ->
ok
end.
Is everything ok here regarding JSON String. I am trying to modify this module.
How to create a JSON Object in Erlang
There are no such things as objects in erlang, so the simple answer is: you can't. However, the things you send over the wire are just strings, and you can certainly create strings using erlang.
To make things easier, you can use an erlang module like jsx to create the json formatted strings that you want to send in your request. However, in order to use erlang modules you will have to learn a little about rebar3
, which is erlang's package installer (see What is the easiest way for beginners to install a module?).
Remember that an http request is just a string that is formatted a certain way. An http request starts with a line like:
POST /some/path HTTP/1.1
Then there are some lines of text called headers, which look like:
User-Agent: Mozilla-yah-yah-bah
Content-Type: application/json
Content-Length: 103
Then there are a couple of newlines followed by some additional text, which is called the post body, which can be in several different formats (the format should be declared in the Content-Type
header):
Format Content-Type
------ -----------
"x=1&y=2" application/x-www-form-urlencoded
"{x:1, y:2}" application/json
"more complex string" multipart/form-data
To make it easier to assemble an http request and send it to a server, erlang has a builtin http client called inets
, which you can read about in the docs here. For an example that uses inets
, see here. Because inets
is a bit cumbersome to use, alternatively you can use a third party http client like hackney. Once again, though, you will need to be able to install hackney
with rebar3
.
Once you send the request, it's up to the server to decipher the request and take the necessary course of action.