Creating an API with Hanami

Hi, all!

I’m a long-time lurker and fan of Hanami. I’ve only messed with it in non-production projects, but finally :raised_hands:, am diving in on a real project I’m building. I’ve started with Hanami 1.2 for this project.

I’m trying to build an API with Hanami, and I’m a little confused on the best way to render JSON. In the past I’ve gotten ERB rendered sites up with no problem. I had a bit of trouble getting JSON to render correctly and I want to make sure I’m not missing anything. Here’s what I’ve done so far:

  • I’ve added an API app to my project.
  • In apps/api/application.rb I’ve set default_request_format and default_response_format to :json
  • I created an action and overrode the Index view to render raw({ foo: 'bar' }.to_json)

My question is: *am I doing this correctly?*I’m able to get this to work properly when hitting the endpoint via Insomnia. Is there anything I’m missing or a better way to do this?

Thank you for your time. :pray:

If I might follow up to that question, as well, I’m getting a ~350ms response time for just rendering that JSON hash. Does that seem normal? That feels a little high, but it could just be my dev environment.

That sounds right to me, and it jives with the docs.

The 350ms is high. Is there any difference when you run it in production mode?

Thank you!

I got the same numbers running in production mode. However, the logs from the server show much shorter response times than Insomnia does. Somewhere under 1ms. I’m not too worried about it at this point, but I’ll keep an eye on it. Thank you, again! I appreciate you taking the time to respond!

1 Like

That really seem pretty abnormal. For that hash you should be seeing at most 2 digit ms.

Can you paste some code from your action?

1 Like

@jasoncharnes I have seen a similar question in gitter chat, please let me paste here a response from “jaypanya”, maybe I t will help you here.

I dig into this and find out that on every request it was loading code every time so when I run server with --no-code-reload argument it worked perfectly and got response in 20-30ms so it looks good

1 Like