Sunday, 18 August 2013

Letting HTML forms make use of JSON APIs

Letting HTML forms make use of JSON APIs

So, I've spent a lot of time writing a cool RESTful API. To simplify, one
can create a new user by performing a POST request to /users.
Great, huh? But now my HTML form wants to create a user. All of its
elements are identical to the arguments that need to be passed to /users.
Therefore, it seems to make a lot of sense for the form to make full use
of this excellent API.
My form resides on /register.html. It's properties are now:
action="/users" method="post". Great integration with my API right
out-of-the-box!
The problem? My RESTful API will respond in JSON, and my form cannot deal
with this response. For example, when an invalid e-mail address is passed,
the returned body may be {"error": 400, "msg": "The given email address is
invalid."}. Instead, register.html should receive this message and display
an appropriate message while allowing the user to fix the input mistake.
An obvious solution would be to not send the form at all, and instead use
AJAX to interact with the API based on the inputs' values. However, this
is far from ideal because the form would be useless for those without
Javascript.
Is there any other approach that I can consider? Or should I not couple
form input with my APIs?
I don't think it matters much, but I'm working with Node.js.

No comments:

Post a Comment