Search code examples
resthttpposterlangcowboy

erlang response http request in decimal instead of letter


I'm beginning using Erlang with Cowboy and Leptus to create a REST API.

So I just tried something simple:

myapp_handler.erl

-module(myapp_handler).
-compile({parse_transform, leptus_pt}).
-export([init/3]).
-export([cross_domains/3]).
-export([terminate/4]).
-export([post/3]).

%% Cross Domain Origin
%% It accepts any host for cross-domain requests
cross_domains(_Route, _Req, State) ->
   {['_'], State}.

%% Start
init(_Route, _Req, State) ->
  {ok, State}.

post("/myRequest", Req, State) ->

  Json = "[
    {
      \"test\": \"hello\"
    }
  ]",

  {200, {json, Json}, State}.

%% End
terminate(_Reason, _Route, _Req, _State) ->
   ok.

After launching the server, I tried to run the POST request through curl:

curl -X POST http://127.0.0.1:8080/myRequest --header "Content-Type:text/json"

And the answer of the request is:

[91,10,32,32,32,32,123,10,32,32,32,32,32,32,34,116,101,115,116,34,58,32,34,104,101,108,108,111,34,10,32,32,32,32,125,10,32,32,93]

All the numbers are the value of the character in decimal from the ascii table. But I wonder why does the answer of the request is displayed in numbers instead of letters. Did I do something wrong?

Thank you in advance


Solution

  • I haven't used Leptus before, but, let's take a look at an example REST endpoint from their README on Github (https://github.com/s1n4/leptus):

    get("/", _Req, State) ->
      {<<"Hello, leptus!">>, State};
    
    get("/hi/:name", Req, State) ->
      Status = ok,
      Name = leptus_req:param(Req, name),
      Body = [{<<"say">>, <<"Hi">>}, {<<"to">>, Name}],
      {Status, {json, Body}, State}.
    

    It appears that if you post a tuple of {json, Term} it will automatically convert your Erlang term to JSON. So instead of making your JSON manually you could instead use:

    post("/myRequest", Req, State) ->
      Json = [{<<"test">>, <<"hello">>}],
      {200, {json, Json}, State}.
    

    It also appears that Leptus is expecting your strings and JSON keys and JSON string values to be passed in as binaries. So if you wanted to return a simple string of output you would use the following:

    post("/myRequest", Req, State) ->
      {200, <<"hello">>, State}.
    

    Typically libraries will use binaries instead of standard Erlang strings because binaries are more efficient than Erlang string lists.