Search code examples
restnaming

REST naming best practice/opinions - is it OK to use just variables without any nouns?


Not sure if I'm using the terminology correctly here, but best explained on example:
Is it generally ok if I use for let's say API for retrieving population count in given area

/population/{state}/{city}/{district}

or I should be using

/population/states/{state}/citys/{city}/districts/{district}

Case A the API returns just one number, depending on how much you specify
Case B the API returns just one number, but you have to always specify every variable, meaning defining just state and city is invalid:

I suppose it is always better to opt for the more explanatory one. Or is there some other logic to it I might be missing?


Solution

  • Generally speaking, with REST endpoints, the '/' indicates that you're accessing a sub-resource. So it really depends on what your trying to do.

    From what I understood, your primary objective is to retrieve a population given a number of parameters.

    So the /population/state/{state}/city/{city}/district/{district} convention will work, if you had something along the following in mind:

    • /population: returns total population
    • /population/states/: returns total population for each state
    • /population/states/{state_name}: returns total population for given state and each of it's constituent cities.
    • and so on

    Note, I used plural for the sub-resource name, i.e. states rather than state.

    If, however, you're only intending to return a single number rather than a breakdown, then an alternative to consider:

    GET /population?state=stateName&city=cityName&district=districtName