我正在尝试使用Erlang构建自己的REST API。我正在按照指南找到:https://github.com/OpenAPITools/openapi-generator/tree/master/samples/server/petstore/erlang-server。
现在我目前停留在最后一点:从Erlang shell运行application:ensure_all_started(http_server).
之后,我认为应用程序正在运行,因为从netstat -nlt | grep LISTEN
我可以看到正在监听127.0.0.1:8080
的过程。例如,如果我尝试运行:
curl -X GET "http://127.0.0.1:8080/v2/pet/44362" -H "accept: application/json"
我没有得到服务器的响应,在服务器上我只看到Attempt to process operation: GetPetById"
,没有其他任何事情发生。我认为它应该返回404错误。
我错过了什么?
你缺少的第一件事是-i
旗帜到curl
。如果您不告诉它,curl
不会打印http响应代码。
$ curl -i -X GET "http://127.0.0.1:8080/v2/pet/44362" -H "accept: application/json"
将显示服务器实际响应http代码401
(未授权),查看GetPetById
的OpenAPI架构(您正在尝试的端点的operationId
)我们可以看到它需要api密钥作为http请求中名为api_key
的头(请参阅OpenAPI架构中的securityDefinitions
部分。所以我们需要的真正的curl
命令是
curl -i -X GET "http://127.0.0.1:8080/v2/pet/2342" -H "api_key: asdf" -H "accept: application/json"
(你可以使用api_key
的任何值)
但是,这不会给出您期望的答案(响应代码404
),而是您将获得501
(未实现)。这是因为openapi生成器工具仅生成您为每个端点处理程序构建实际逻辑所需的脚手架。生成器工具无法知道您希望如何处理传入的请求,因此它生成一个返回501
响应的通用处理程序。
查看openapi_default_logic_handler.erl
文件,在那里你会发现handle_request/3
是请求处理程序。处理GetPetById
端点的最小变化是:
handle_request('GetPetById', _Req, _Context) ->
% This is a hardcoded 404 response for all id's.
% add your logic here to e.g try to fetch the id from a database
{404, #{}, #{}};
handle_request(OperationID, Req, Context) ->
error_logger:error_msg(
"Got not implemented request to process: ~p~n",
[{OperationID, Req, Context}]
),
{501, #{}, #{}}.
另请注意,在文件openapi_default_logic_handler.erl
中定义了函数authorize_api_key/2
is。您可以在此处实现api_key
标头值的验证,默认情况下它允许任何值。