-
-
Notifications
You must be signed in to change notification settings - Fork 6.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Websocket Routes Only Work on FastAPI, not APIRouter #98
Comments
Just tested it out! I'm impressed at how quickly that was fixed, thanks! |
Awesome! Kudos to @euri10 for his work 😀🍰🌮 Thanks @iwoloschin for reporting back and closing the issue. |
This comment has been minimized.
This comment has been minimized.
@brunopcarv This is a 2 years old issue... You'll have better chances of getting help if you create a new one. 😗 |
Looks like this bug again comes in the APIRouter prefix is not getting utilized in
|
the same bug is present in version 0.65.1 |
I have same issue with API-Router. return
UPDATE I was trying with another way. The Result is, it's working in websocket method : # ws.py
from fastapi import FastAPI, WebSocket
from fastapi.middleware.cors import CORSMiddleware
ws = FastAPI()
# Your CORS
ws.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# websocket
@ws.websocket("/")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Message text was: {data}") main file : import uvicorn
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
# import ws.py for 'mounted'
from ws import ws
app = FastAPI()
# Your CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# mount ws.py
app.mount("/ws", ws)
# ... your routes OR something ...
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000) I feel like, it's better way to use in |
same error in 0.68.1 |
I have the same issue at the moment if i set the prefix param in server
client
|
I am also facing the exact same issue. I am getting a 403 error for websockets under routers with prefix. It works without the prefix. |
* As seen in fastapi/fastapi#98 and fastapi/fastapi#2634 websocket does not currently inherit the route prefix correctly, as such patch it to keep the websocket consistent with the rest of the file * Also move userID to path parameters since websockets dont support body parameters
* As seen in fastapi/fastapi#98 and fastapi/fastapi#2634 websocket does not currently inherit the route prefix correctly, as such patch it to keep the websocket consistent with the rest of the file * Also move userID to path parameters since websockets dont support body parameters
same error in 0.70.0 |
Still getting this issue on |
Same issue as mentioned @nanacnote |
Same issue in fastapi==0.74.0 |
Running into same issue, can that fix be included soon? |
Same issue in fastapi==0.75.1 |
Hi everyone thanks for the help and for fixing this issue. Truthfully the WebSocket fix works in development (Uvicorn server), however, in production (Ubuntu environment) the websocket did not connect to the APIRouter specified. For the WebSocket to connect I used the /ws (test.com/ws) rather than the route I specified (test.com/test/flow/ws). |
Another thing I noticed is that the WebSocket does not reflect in the Docs. Although the OpenAPI doc added is the 3.0 version which should be able to document websocket endpoints. |
@Kludex I don't get the reason you are sending emojis such as the down thumb and all. it's better to ignore than act funny. |
I sent emojis to show how I feel about your comments. I didn't mean to offend you. Let me explain why:
There can't be a possible scenario on which it has a different behavior depending on the environment (prod vs dev) because of this issue. It can be because of other factors, but not because of this one.
This comment is not true. OpenAPI docs doesn't support In any case, it's always better to open a new issue than engaging on a closed issue. It avoids users to believe the issue was wrongly closed. |
@Kludex Thanks for your explanation. To be fair I was not even pointing to this issue, and I agree that it could be something else. I was just bringing it forward (hoping) someone had experienced that and there is a fix to it. With regards to OpenAPI documentation, thank you for clarifying that, I read it somewhere and I believed it (I also saw the OpenAPI swagger package on PyPI that suggested something along that line). Thank you for your reply and all you do in the FastAPI community. Continue to have an awesome day. |
same issue in |
Hey @Hyperx837 yeah. You should consider creating another instance of the FastAPI application, create a WebSocket with the newly created app instance and then mount it on the Base App where the core application routers live. |
same issue in fastapi==0.88.0 i should use FastAPI instead of APIRouter.... update ok, it works, well in two files. If all in one file, should like this order: router = APIRouter(prefix="/ws")
@router.websocket("/asr")
async def websocket_a(ws_a: WebSocket):...
app = FastAPI()
app.include_router(router) not this: router = APIRouter(prefix="/ws")
app = FastAPI()
app.include_router(router)
@router.websocket("/asr")
async def websocket_a(ws_a: WebSocket):... @Hyperx837 u could have a try |
@hscspring thank you so much for your clear reply! That was the solution for me: replaced |
@Lopofsky what FastAPI version are you using? This is not working for me with 0.97.0. Getting the 403 error with websocket endpoints defined in other routes files. Using |
@papapumpnz |
after update 0.95 to 0.100.1, I fix this problem |
I'm still getting this with 0.101.0. Everything works if I |
I confirm with @AntonOfTheWoods . Currently (22 Aug 2023 at 17:20 UTC) the latest version of FastAPI is old codechat_ws.py from fastapi import APIRouter, WebSocket
chat_socket = APIRouter()
@chat_socket .websocket("/chat")
async def handle_ws(ws: WebSocket):
await ws.accept()
while True:
string = await ws.receive_text()
await websocket.send_text(string) main.py from fastapi import FastAPI
from . import chat_socket
app = FastAPI()
app.add_websocket_route("/ws", chat_socket) EditTurns out my previous code was wrong, the prefix has to be the same on both the include statement and in the router code. This is for chat_ws.py from fastapi import APIRouter, WebSocket
chat_socket = APIRouter()
@chat_socket .websocket("/chat")
async def handle_ws(ws: WebSocket):
await ws.accept()
while True:
string = await ws.receive_text()
await websocket.send_text(string) main.py from fastapi import FastAPI
from . import chat_socket
app = FastAPI()
app.add_websocket_route("/chat", chat_socket) |
|
I had the same error when using Python
from fastapi import WebSocket, APIRouter
router = APIRouter(
prefix="/ws"
)
@router.websocket("/pub/{channel_id}")
async def ws_endpoint(websocket: WebSocket):
# ...
import uvicorn
from fastapi import FastAPI
from ws import ws
app = FastAPI()
app.include_router(ws.router)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000) |
This was solved years ago, if you encounter a similar issue, please open a discussion. |
Describe the bug
Websocket routes appear to only work on the main FastAPI object, not on APIRouter objects. When the same function is copied from a FastAPI object to an APIRouter object instead of working properly it just throws a 403.
To Reproduce
Steps to reproduce the behavior:
hello
to an APIRouter fails:Expected behavior
I expect a websocket route to work on both a FastAPI and APIRouter object.
Screenshots
Not applicable.
Environment:
OS: macOS 10.14.3
FastAPI Version: 0.9.0
Python version, get it with: 3.7.2
Additional context
Testing websocket client side with
websocat
.The text was updated successfully, but these errors were encountered: