Search code examples
resthttpwebsocketserver-sent-eventsevent-stream

What is event stream in rest api and why do we need it?


I'm trying to develop rest api for the first time. And looking to loopback references that uses change stream for the resources like /resources/change-stream with the GET and POST methods.

I have visited this post which indicates differences between rest api and streaming api.

While the loopback is providing it in rest api, I think. What is it and what it does. Can you please explain it to me in a way that you're making clear to me (for a six years old child). Because, I am developing REST API for the first time in my own. So, I would like to understand step by step if possible like what should I have in the postman. Should I use the url like '/api/resources/change-stream?_format=event-stream along with application/json content-type or just /api/resources/change-stream would be fine.

It would be great example if you could provide me some real example so that I can develop it trying in my own application.

PS: It's perfectly fine to me whichever language (Node.js, Python, Ruby, PHP) you'd choose to provide answer with some examples.


Solution

  • If I had to guess, it sounds like a 1-way long polling where you leave a long running, open request to a server that will fulfill the request when an event happens. If the request times out, don't worry about it, send another and leave it open. When the request is fulfilled with an event, immediately fire another request so that you can receive the next event.

    Since the document on the other end of the API is still (probably) a JSON document, you should keep that mime. However, you aren't limited in what you can send back as an event type; if you want to send back XML or YAML, do so and set that mime. The "stream" is just a convention mechanism.

    As far as your application is concerned and from a REST perspective, it just takes a while for the event that you are trying to get to be provided to you and it has a high chance of failure. But I wouldn't look at this from a REST perspective, REST is just convention, don't let it tie you down.

    Alternatively, long-polling should probably be replaced by something like a WebSocket as it provides a much easier API (in my opinion) and doesn't seem as hacky as long-polling.

    If you're trying to ask, "how do I tell a RESTful consumer that my API is a 'stream' API", there is not point. Again, as far as REST is concerned, the https://example.com/api/events/ endpoint refers to a JSON type document that changes a lot, takes a long time to receive, and "fails" often (if the events you generate don't fire a lot).