Suppose that I have a nested one to many-type hierarchy database as follows:
One Region has many Countries; each Country has many Cities; a City must belong to one and only one country.
Abstracting this information into a RDBMS is a trivial exercise, but (to my mind) the most sensible REST endpoint to return a list of countries for a given region id would be something like the following:
HTTP GET http://localhost/Region/3/Countries
By default, the .NET Web API's routing would be, at best, http://localhost/Countries/Region/3
or http://localhost/Region/Countries/3
.
Is there a sensible naming-convention I should follow, or is the routing customisable enough to allow URIs to take any shape I like?
Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing. As the name implies, attribute routing uses attributes to define routes. Attribute routing gives you more control over the URIs in your web API.
Routing in ASP.NET Core Web API application is the process of mapping the incoming HTTP Request (URL) to a particular resource i.e. controller action method. For the Routing Concept in ASP.NET Core Web API, we generally set some URLs for each resource.
In the custom routing mode MVC sites respond to incoming requests using standard ASP.NET routing. Page URLs are determined by the routes that you register into your MVC application's routing table.
API routes provide a solution to build your API with Next.js. Any file inside the folder pages/api is mapped to /api/* and will be treated as an API endpoint instead of a page . They are server-side only bundles and won't increase your client-side bundle size.
The routing should be customizable enough to get the URLs you're looking for. Assuming you want URLs in the form 'http://localhost/Region/3/Countries', you could register this custom route:
config.Routes.MapHttpRoute("MyRoute", "Region/{regionId}/Countries", new { controller = "Region", action = "GetCountries" });
This would dispatch requests to the 'GetCountries' action on the 'RegionController' class. You can have a regionId parameter on the action that gets model bound automatically for you from the URI.
You may want to look online for the attribute routing package for WebAPI since it may be more appropriate in your case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With