I am building a website that would serve dynamic content. All communication between server/browser in through REST. PostgreSQL is used as a datastore.
My question is for any GET request, should i be building the html on the fly (along with the dynamic content).
As an example
@GET
@Produces(MediaType.TEXT_HTML)
public String getAllEmployee() {
// employees fetched from the data base
String html = "<HTML></head> blah blah";
return html;
}
My question is should the html be built on the fly and and sent back to the browser.
Also how does big websites like linkedin works? Do they generate the html page on the fly and send back the page?
Another method I could think of is send the barebones html with AJAX request embedded into it. And then the ajax request fetches the dynamic content from the server.
One of the core benefits of REST is its separation of representation (encoding) from the underlying resource being accessed.
It's perfectly fine to return HTML if the client requests it as a preference via the Accept
header. If the client indicates that it prefers JSON or XML or whatever other super-duper encoding is dreamed up next year, then your server can return that format instead, and your URI scheme won't change one bit.
Most importantly, don't forever tie your REST API to a single encoding format. Take advantage of the wonderful flexibility that HTTP content negotiation offers you as an API service provider, and that way you can give your API clients the ability to pick and choose the most appropriate format for their needs.
There's no hard and fast rule, however, REST services typically return data in some interchange format such as XML or JSON. The client code would then interpret the results into HTML and inject them into the page as you deem appropriate. Sending HTML already prepared may not be desirable because
- It limits what your API clients can do with the data
- Your service layer must determine the presentation format, which is typically undesirable
- Means your service may be returning more bits over the wire than is necessary, which can make a great difference if you have a busy site.
I would recommend that you send JSON objects back, and have the client code apply the resulting objects against a template of some sort (there are lots of ways to do this) to generate the actual HTML.