MVC Web API, get sub items

I have a database with two tables. Countries and Cities where each city has a relation to a spesific country.

In my ASP.Net Web API I can get a list of countries by a GET request to http://example.com/api/countries to run the CountriesController. And I can get details about a country by http://example.com/api/countries/1.

If I want a list of all cities for a country the REST query URL should be http://example.com/api/countries/1/cities? And details for a City http://example.com/api/countries/1/cities/1

How can I accomplish this in ASP.Net Web API?

Upvotes: 2

Views: 1245

Answers (1)

Mirko
Mirko

Reputation: 4282

How about this, in global.asax.cs define an additional api route like so:


routes.MapHttpRoute(
    name: "CityDetail",
    routeTemplate: "api/countries/{countryid}/cities/{cityid}",
    defaults: new { controller = "Cities" }
);

Then define a new CitiesController like so:


public class CitiesController : ApiController
{
    // GET /api/values
    public IEnumerable Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET /api/values/5
    public string Get(int countryId, int cityid)
    {
        return "value";
    }

    // POST /api/values
    public void Post(string value)
    {
    }

    // PUT /api/values/5
    public void Put(int countryId, int cityid, string value)
    {
    }

    // DELETE /api/values/5
    public void Delete(int countryId, int cityid)
    {
    }
}

Needless to say you might want to improve the controller implementation a bit :)

Upvotes: 3

Related Questions