Best practise for trailing slashes on endpoints #5105
-
|
I have noticed that sometimes trailing slashes are used, and sometimes they are not used for API endpoints. Is it best practice to define the endpoint with a trailing slash or without a trailing slash? What do you need to consider when designing? ExampleFor example, take this app: from fastapi import FastAPI
app = FastAPI()
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]
@app.get("/items2")
async def read_item2(skip: int = 0, limit: int = 10):
return fake_items_db[skip : skip + limit]Using a trailing slash
|
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 1 reply
-
|
I personally do not like trailing slashes because you are accessing RESOURCE. You can also look at this like you are accessing file: Try to answer this: How will you put query parameters when you have slash at the end? |
Beta Was this translation helpful? Give feedback.
-
|
Personally, I prefer not to add trailing slashes at the end of paths. |
Beta Was this translation helpful? Give feedback.
-
There is no magic, Fastapi returns 307 redirects, you can add the |
Beta Was this translation helpful? Give feedback.
-
|
There is no strict rule, but seems that most people prefer not to add trailing slashes. Spectral (popular linting tool for openapi) by default has |
Beta Was this translation helpful? Give feedback.
-
|
If you follow RESTFUL api design, you would avoid using trailing slash in most cases. The general rule is that, you use static path for a collection of resources, such as /users, use /users/{user_id} for a particular resource(user with user_id)。 /users/ is misleading and often error prone as it seems to suggest you are operating on user with user_id None or "" |
Beta Was this translation helpful? Give feedback.
There is no strict rule, but seems that most people prefer not to add trailing slashes.
Spectral (popular linting tool for openapi) by default has
path-keys-no-trailing-slashrule enabled (ensures there is no trailing slashes).