WebSockets¶
When defining WebSockets, you normally declare a parameter of typeWebSocket and with it you can read data from the client and send data to it.
Read more about it in theFastAPI docs for WebSockets
It is provided directly by Starlette, but you can import it fromfastapi:
fromfastapiimportWebSocket
Tip
When you want to define dependencies that should be compatible with both HTTP and WebSockets, you can define a parameter that takes anHTTPConnection instead of aRequest or aWebSocket.
fastapi.WebSocket¶
WebSocket(scope,receive,send)
Bases:HTTPConnection
Source code instarlette/websockets.py
| def__init__(self,scope:Scope,receive:Receive,send:Send)->None:super().__init__(scope)assertscope["type"]=="websocket"self._receive=receiveself._send=sendself.client_state=WebSocketState.CONNECTINGself.application_state=WebSocketState.CONNECTING
|
client_stateinstance-attribute¶
application_stateinstance-attribute¶
url_for¶
url_for(name,/,**path_params)
Source code instarlette/requests.py
| defurl_for(self,name:str,/,**path_params:Any)->URL:url_path_provider:Router|Starlette|None=self.scope.get("router")orself.scope.get("app")ifurl_path_providerisNone:raiseRuntimeError("The `url_for` method can only be used inside a Starlette application or with a router.")url_path=url_path_provider.url_path_for(name,**path_params)returnurl_path.make_absolute_url(base_url=self.base_url)
|
receiveasync¶
Receive ASGI websocket messages, ensuring valid state transitions.
Source code instarlette/websockets.py
3536373839404142434445464748495051525354555657 | asyncdefreceive(self)->Message:""" Receive ASGI websocket messages, ensuring valid state transitions. """ifself.client_state==WebSocketState.CONNECTING:message=awaitself._receive()message_type=message["type"]ifmessage_type!="websocket.connect":raiseRuntimeError(f'Expected ASGI message "websocket.connect", but got{message_type!r}')self.client_state=WebSocketState.CONNECTEDreturnmessageelifself.client_state==WebSocketState.CONNECTED:message=awaitself._receive()message_type=message["type"]ifmessage_typenotin{"websocket.receive","websocket.disconnect"}:raiseRuntimeError(f'Expected ASGI message "websocket.receive" or "websocket.disconnect", but got{message_type!r}')ifmessage_type=="websocket.disconnect":self.client_state=WebSocketState.DISCONNECTEDreturnmessageelse:raiseRuntimeError('Cannot call "receive" once a disconnect message has been received.')
|
sendasync¶
Send ASGI websocket messages, ensuring valid state transitions.
Source code instarlette/websockets.py
59606162636465666768697071727374757677787980818283848586878889909192939495969798 | asyncdefsend(self,message:Message)->None:""" Send ASGI websocket messages, ensuring valid state transitions. """ifself.application_state==WebSocketState.CONNECTING:message_type=message["type"]ifmessage_typenotin{"websocket.accept","websocket.close","websocket.http.response.start"}:raiseRuntimeError('Expected ASGI message "websocket.accept", "websocket.close" or "websocket.http.response.start", 'f"but got{message_type!r}")ifmessage_type=="websocket.close":self.application_state=WebSocketState.DISCONNECTEDelifmessage_type=="websocket.http.response.start":self.application_state=WebSocketState.RESPONSEelse:self.application_state=WebSocketState.CONNECTEDawaitself._send(message)elifself.application_state==WebSocketState.CONNECTED:message_type=message["type"]ifmessage_typenotin{"websocket.send","websocket.close"}:raiseRuntimeError(f'Expected ASGI message "websocket.send" or "websocket.close", but got{message_type!r}')ifmessage_type=="websocket.close":self.application_state=WebSocketState.DISCONNECTEDtry:awaitself._send(message)exceptOSError:self.application_state=WebSocketState.DISCONNECTEDraiseWebSocketDisconnect(code=1006)elifself.application_state==WebSocketState.RESPONSE:message_type=message["type"]ifmessage_type!="websocket.http.response.body":raiseRuntimeError(f'Expected ASGI message "websocket.http.response.body", but got{message_type!r}')ifnotmessage.get("more_body",False):self.application_state=WebSocketState.DISCONNECTEDawaitself._send(message)else:raiseRuntimeError('Cannot call "send" once a close message has been sent.')
|
acceptasync¶
accept(subprotocol=None,headers=None)
Source code instarlette/websockets.py
100101102103104105106107108109110 | asyncdefaccept(self,subprotocol:str|None=None,headers:Iterable[tuple[bytes,bytes]]|None=None,)->None:headers=headersor[]ifself.client_state==WebSocketState.CONNECTING:# pragma: no branch# If we haven't yet seen the 'connect' message, then wait for it first.awaitself.receive()awaitself.send({"type":"websocket.accept","subprotocol":subprotocol,"headers":headers})
|
receive_textasync¶
Source code instarlette/websockets.py
| asyncdefreceive_text(self)->str:ifself.application_state!=WebSocketState.CONNECTED:raiseRuntimeError('WebSocket is not connected. Need to call "accept" first.')message=awaitself.receive()self._raise_on_disconnect(message)returncast(str,message["text"])
|
receive_bytesasync¶
Source code instarlette/websockets.py
| asyncdefreceive_bytes(self)->bytes:ifself.application_state!=WebSocketState.CONNECTED:raiseRuntimeError('WebSocket is not connected. Need to call "accept" first.')message=awaitself.receive()self._raise_on_disconnect(message)returncast(bytes,message["bytes"])
|
receive_jsonasync¶
receive_json(mode='text')
Source code instarlette/websockets.py
130131132133134135136137138139140141142 | asyncdefreceive_json(self,mode:str="text")->Any:ifmodenotin{"text","binary"}:raiseRuntimeError('The "mode" argument should be "text" or "binary".')ifself.application_state!=WebSocketState.CONNECTED:raiseRuntimeError('WebSocket is not connected. Need to call "accept" first.')message=awaitself.receive()self._raise_on_disconnect(message)ifmode=="text":text=message["text"]else:text=message["bytes"].decode("utf-8")returnjson.loads(text)
|
iter_textasync¶
Source code instarlette/websockets.py
| asyncdefiter_text(self)->AsyncIterator[str]:try:whileTrue:yieldawaitself.receive_text()exceptWebSocketDisconnect:pass
|
iter_bytesasync¶
Source code instarlette/websockets.py
| asyncdefiter_bytes(self)->AsyncIterator[bytes]:try:whileTrue:yieldawaitself.receive_bytes()exceptWebSocketDisconnect:pass
|
iter_jsonasync¶
Source code instarlette/websockets.py
| asyncdefiter_json(self)->AsyncIterator[Any]:try:whileTrue:yieldawaitself.receive_json()exceptWebSocketDisconnect:pass
|
send_textasync¶
Source code instarlette/websockets.py
| asyncdefsend_text(self,data:str)->None:awaitself.send({"type":"websocket.send","text":data})
|
send_bytesasync¶
Source code instarlette/websockets.py
| asyncdefsend_bytes(self,data:bytes)->None:awaitself.send({"type":"websocket.send","bytes":data})
|
send_jsonasync¶
send_json(data,mode='text')
Source code instarlette/websockets.py
| asyncdefsend_json(self,data:Any,mode:str="text")->None:ifmodenotin{"text","binary"}:raiseRuntimeError('The "mode" argument should be "text" or "binary".')text=json.dumps(data,separators=(",",":"),ensure_ascii=False)ifmode=="text":awaitself.send({"type":"websocket.send","text":text})else:awaitself.send({"type":"websocket.send","bytes":text.encode("utf-8")})
|
closeasync¶
close(code=1000,reason=None)
Source code instarlette/websockets.py
| asyncdefclose(self,code:int=1000,reason:str|None=None)->None:awaitself.send({"type":"websocket.close","code":code,"reason":reasonor""})
|
WebSockets - additional classes¶
Additional classes for handling WebSockets.
Provided directly by Starlette, but you can import it fromfastapi:
fromfastapi.websocketsimportWebSocketDisconnect,WebSocketState
fastapi.websockets.WebSocketDisconnect¶
WebSocketDisconnect(code=1000,reason=None)
Bases:Exception
Source code instarlette/websockets.py
| def__init__(self,code:int=1000,reason:str|None=None)->None:self.code=codeself.reason=reasonor""
|
reasoninstance-attribute¶
When a client disconnects, aWebSocketDisconnect exception is raised, you can catch it.
You can import it directly formfastapi:
fromfastapiimportWebSocketDisconnect
Read more about it in theFastAPI docs for WebSockets
fastapi.websockets.WebSocketState¶
Bases:Enum
CONNECTINGclass-attributeinstance-attribute¶
CONNECTEDclass-attributeinstance-attribute¶
DISCONNECTEDclass-attributeinstance-attribute¶
RESPONSEclass-attributeinstance-attribute¶
WebSocketState is an enumeration of the possible states of a WebSocket connection.