Hacker News new | ask | show | jobs
by deniz-a 1663 days ago
You don't return HTML from API endpoints, you return it from your UI endpoints. You could reuse those for JSON with content negotiation, or have a frontend server+backend server setup where the backend server is also a public API, or some other solution.
1 comments

Semantics over the name aside, you end up returning small chunks of HTML from newly defined routes that are only useful for your HTMX frontend, hence my usage of API as the interface really only makes sense to the machine and not the user without the rest of the page content.

Yes you could inspect the headers and such to determine what type to return, but the core problem remains, that the HTML in those is not reusable whereas as JSON would be.

How much overhead this is for you depends on your design of course, but it does mean some work might potentially be wasted if you go down the full SPA application later and even if not changing layouts and such might be a pain.

Thanks for HTMX and your essays. Today I was reading HTMX documentation on what to do when we design API-first for a particular project but don't want any of the frontend magic aka SPA. I found immediately that I need to use both json_enc and client-side-templates extensions. Hope I am on the right path.
hi animesh, that would only be the case if you are trying to retrofit htmx on top of an existing JSON API

if it is greenfield development, it is much better to simply return SSR HTML and avoid that complexity

you can join the discord for more immediate help:

https://htmx.org/discord

That makes sense. I didn't think about it that way, but traditional MVC views would do just as well I guess for greenfield work.
> Semantics over the name aside, you end up returning small chunks of HTML from newly defined routes that are only useful for your HTMX frontend, hence my usage of API as the interface really only makes sense to the machine and not the user without the rest of the page content.

Web2py (being phased out by py4web which I haven't tried) made that very easy. If your api is accessed as api/hello.html, it can return HTML. According to the extension, hello.json, hello.csv, hello.txt, hello.pdf, etc. can return the adequate content.

Of course you can always return JSON regardless of the extension, but I found the same endpoints serving different formats very convenient.