简体   繁体   中英

API: GET-request with user_id or name+region

In my API I have a GET /users/ which gets me an array of all documents in users-collection. And I have a GET /users/:user_id which gets me a user. I also want to have a GET /users/name.region which gets me one user. Is this possible?

Do I have to use query params like GET /users/name="Joe"&region="US"? How would I have to implement this? In another endpoints or is there a way of checking if its either a user_id or the combination of name and region?

Something like this?

if !req.params{
model.find({"name":query.params.name, "region": query.params.region})}
else
model.find({"user_id": req.params.user_id}) 

Maybe you can do it with the same route...

An exemple

const givenId = req.params.user_id;
const parts   = givenId.split('.');

if (parts.length === 2) {
    const name   = parts[0];
    const region = parts[1];
} else { 
    const userId = givenId;
}

Usually having something different than GET users/:id will break most popular REST guides like Google's Resource Name specs .

What would be much better to do is have a GET users/search end-point which accepts various query parameters, such as name and region and give the desired query of users.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM