2

This is my first time using erlang and I decided to try and write a wrapper for an API. Here's what I've got so far:-

            -module(my_api_wrapper).

            %% API exports
            -export([auth/0]).

            auth() ->
                application:start(inets),
                application:start(ssl),
                AuthStr = base64:encode_to_string("username:password"),

                Method = post,
                URL = "https://api.endpoint.com/auth",
                Header = [{"Authorization", "Basic " ++ AuthStr}],
                Type = "application/json",
                Body = "{\"grant_type\":\"client_credentials\"}",
                HTTPOptions = [],
                Options = [],
                httpc:request(Method, {URL, Header, Type, Body}, HTTPOptions, Options).

When testing this at the shell I get an error:-

{error,{failed_connect,[{to_address,{"api.endpoint.com",
                                 443}},
                    {inet,[inet],closed}]}}

I can't figure out what I'm doing wrong here! I'm running this version Erlang/OTP 19 [erts-8.0.2]. Any help appreciated.

overture8
  • 109
  • 2
  • 7
  • 3
    Does the answer on this question help: http://stackoverflow.com/questions/38620111/connection-closed-strange-error-unable-to-connect-from-erlang-vm-to-certain-h? – Dogbert Sep 25 '16 at 09:04
  • Yes! That helped me get it fixed. Thanks for your help! – overture8 Sep 25 '16 at 18:53
  • 2
    A general tip: I'd recommend using `{ok, _} = application:ensure_all_started(ssl)` -- ask OTP to handle the application dependencies and make sure that the application actually started. – Nathaniel Waisbrot Sep 25 '16 at 23:09

1 Answers1

2

For anyone who it might help - here's exactly what I changed to make the code in my original question work - thanks to Dogbert for his comment above.

        -module(my_api_wrapper).

        %% API exports
        -export([auth/0]).

        auth() ->
            application:start(inets),
            application:start(ssl),
            AuthStr = base64:encode_to_string("username:password"),

            Method = post,
            URL = "https://api.endpoint.com/auth",
            Header = [{"Authorization", "Basic " ++ AuthStr}],
            Type = "application/json",
            Body = "{\"grant_type\":\"client_credentials\"}",
            % ADD SSL CONFIG BELOW!
            HTTPOptions = [{ssl,[{versions, ['tlsv1.2']}]}], 
            Options = [],
            httpc:request(Method, {URL, Header, Type, Body}, HTTPOptions, Options).
overture8
  • 109
  • 2
  • 7