fastapi: prefix parameter in APIRouter does not work for websocket

# main.py
from fastapi import FastAPI
import myroute

import myroute
app = FastAPI()
app.include_router(myroute.router)

@app.get("/")
async def root():
    return {"message": "hello world!!"}
# myroute.py
from fastapi import APIRouter

router = APIRouter(prefix="/prefix")

# you'd expect ws://localhost:800/prefix/ws to work but only ws://localhost:800/ws connects
@router.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):

    await websocket.accept()
    await websocket.send_text("hi")
    await websocket.close()

# this works fine if you go to http://localhost:8000/prefix
@router.get("/")
def read_root():
    return {"Hello": "World"}

Description

Hi,

So with APIRouter(), the prefix path does not seem to be prepended to the websocket router path. Not sure if its by design but if it is I feel like its quite misleading

Environment

  • OS: macOS Catalina 10.15.4

  • FastAPI Version: 0.63.0

  • Python version: 3.8.2

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 13
  • Comments: 15 (2 by maintainers)

Most upvoted comments

I’d also highly appreciate #2640 being merged.

Same here, I would really appreciate this PR to be merged

Hi I would like to say that this is quite important, as I would like to move code out of the main.py file, and this feature would help me to do so…

Still waiting over here as well.

Hope this PR to be merged soon.

Waiting too…

@tiangolo

Thanks for the report @schen96!

And thanks @Kludex for the quick fix in https://github.com/tiangolo/fastapi/pull/2640! Sorry for the delay, there are lots of PRs to review. 😅

The fix will be available in FastAPI version 0.75.2, released in a couple of hours. 🚀