API Specific Projects

Menu
Menu

APIs

API Specific Projects

Visual Studio comes with a project template to create an application that just provides API Endpoints

Create a new project with:

Quick Start Create a new project

Select "ASP.NET Core Web Application" from the options available.

Choose Core Web Application

Name the Project "MyGameAPI".

Configure Your Project

Select .NET Core from the drop-down and "API" from the list.

For this purposes of this lab uncheck Configure for HTTPS.

API Project

Exploring the Default API Application

Visual Studio creates a application themed around weather. The file structure is as follows:

API Weather Forecast Set Up

Running the applicaiton will produce a the following:

Weather Output

Note:

The above is the resulting of viewing the output in Google Chrome with the JSON formatter extension installed.

Exploring the Model, Startup.cs and Controller

The above output is based on WeatherForecast.cs Model located at the root of the application.

Model: WeatherForecast.cs

To see how the output was generated we'll begin with Startup. file. The file differs from the MVC project through the way Endpoints are set. As this is not a MVC application there is no default routing set out, instead endpoints are mapped by the controllers.

Startup.cs

Open the Controllers/WeatherForecastController.cs file. The Controller has the attributes:

A technique known as Attribute Routing is used to creates routes of localhost:5000/api/Films for each of types of HTTP requests.

The [ApiController] attribute indicates that the controller responds to web API requests.

ASP.NET was designed for modern web experiences. Endpoints automatically serialize your classes to properly formatted JSON. One affect of this automatic serialization is that the Model is converted to camelCase, in that TemperatureC in the model becomes temperatureC in the JSON output.

As such the action:

... returns an IEnumberable serialized* to JSON. (The above action is called Get() purely because it makes sense to do so. It could be renamed to any other valid method name.)

* Serializing describes converting an object into a string. We serialize the C# IEnumerable into a string so that it can be transported via HTTP.