Recommendation on how to document Websocket API
I've written a Websocket-API using socket.io.
Let's say that after establishing the connection the server waits for a login
-event with a payload like {username: String, password: String}
.
The server then answers with the events login:accept
or login:deny
.
Only if the login was successful the server then responds to an event tweets:get
with an event tweets
(that has an array of tweets as payload).
Is there a standardized way to document APIs like this one? Do you have any recommendations and experiences?
There's AsyncApi node tool to create machine-readable definitions, it's very similar to swagger but for asynchronous APIs, and there are tools to generate HTML such as AsyncApi docgen and widdershins.
You can build your documentation using either yaml
or json
, as an example:
asyncapi: "1.0.0"
topics:
"tweets:get":
publish:
$ref: "#/components/messages/getTweets"
tweets:
subscribe:
$ref: "#/components/messages/tweetsList"
Where topics
= events
, publish
= emit
, and subscribe
= on
in socket.io terms
after saying that, authentication using socket.io mostly depends on tokens, the user would send authentication token in the options.query
at the connection initiation time, and you authenticate the token at the backend, then you can disconnect the connection if authentication failed. No need for login:accept
or login:deny
const socket = io('http://localhost?token=abc');
// or
const socket = io({ query: { token: 'cde' } });
链接地址: http://www.djcxy.com/p/31782.html