2

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?

tereško
  • 58,060
  • 25
  • 98
  • 150

1 Answers1

3

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 :)

Mirko
  • 4,284
  • 1
  • 22
  • 19
  • 1
    Thank you very much! To get http://example.com/countries/1/cities to return a collection of cities for the given country I had to implement: // GET /api/values public IEnumerable Get(int countryId) { return new string[] { "value1", "value2" }; } – Øystein Kalvø Stephansen May 14 '12 at 09:37