Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I made a UI with htmx, it works great.

But now I want to add a JSON API to the program: I could reuse the same routes (/create, etc), but require an application+json header; or add a full /api/ component essentially duplicating the logic from the main app.

Neither option is great.



Fat services, thin routes. Try moving your business logic to a library and consume it from both your UI and API routes. That minimizes duplication and decouples your public API resolvers (with backwards compatibility requirements etc) from your private UI resolvers (which you want to evolve rapidly to optimize your UIX).

That's what we did and it works pretty well in practice.


I do get kind of annoyed that htmx submits forms using form url encoding. It's non trivial to validate, see https://igor.moomers.org/posts/zod-schemas-htmx

As a result for POST requests you have to have htmx routes that accept urlencode and API routes that accept JSON, and JSON is far superior. But for outputs I actually think separating your UI and API is helpful. The code reuse is not worth the entanglement of concerns.


Ok, for the sake of completeness–why do you want to add a JSON API to the program? Quite a lot depends on the reason.


It's a service, and I want to add a CLI for humans and agents. Aeolos' reply makes a lot of sense, I can refactor the backend into a library and add thin UI and API routes on top of it.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: