Shared Data Contracts

Most Web applications today must interact with the server in some way to get and send data, and this is typically done with the HTTP protocol. With Angular propelling TypeScript into mainstream Web app development, we have new opportunities for communicating with the server through strong typing over HTTP. For a long time, server-side languages like Java and C# have used strong typing to provide more control and confidence over data type alignment through data contracts.

A data contract is an assurance that data types between two systems, services, or in the case, the server and browser align. This can prevent numerous bugs and catch problems like case mismatches, misspelling, and changed attributes before they show up in production. This becomes even more helpful when using TypeScript tools to help autocomplete property names and view what properties are available without having to look through documentation.

API Contract with OpenAPI

For the server and client to communicate through data contracts, there must be a common agreement on how to format messages. Although multiple specifications have been developed for HTTP communication, Swagger developed one of the most popular specifications called OpenAPI.  OpenAPI provides a way to express an API which can be displayed for humans to read, or in JSON format for usage by tooling or other applications.

Swashbuckle is a middleware for ASP.Net Web API that automatically creates a swagger JSON file and user interface with very little work to implement.

Swashbuckle Setup

Simply install the Swashbuckle.AspNetCore package and then add the basic configuration in the Startup.cs file for .Net Core, :

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "Tour of Heros API", Version = "v1" });
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseMvc();

    app.UseSwagger();

    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Tour of Heros API v1");
    });
}

Next, startup the .Net Core API and go to /swagger endpoint to view the Swagger UI. The generated data contract for the API will be at /swagger/v1/swagger.json.

 

Generated Tour of Herios API in Swagger UI Generated Tour of Herios API in Swagger UI

 

Generating Angular Code from an OpenAPI Contract

Now that we have a generated swagger.json file available from our .Net Core API server, we make use of it with Angular and Typescript to generate not only the models but also the Angluar API module and services for use within our Angular application. After trying multiple OpenAPI TypeScript and Angular code generators, my favorite so far is ng-swagger-gen. The library is compatible with Swagger 2.0 and Angular 4.3+ and provides many great features including Angular module and service generation in addition to the models.

ng-swagger-gen Setup

To configure the swagger generator in a new Angular CLI application, first run:

npm i ng-swagger-gen

This will install the library. Add a new command to the package.json file under the scripts section "api": "ng-swagger-gen -i http://localhost:30628/swagger/v1/swagger.json",.  Just be sure to change the path to the swagger JSON URL configured in the previous section. Finally, start the server API and run:

npm run api

Running the api command we just created will generate all the code necessary to call your API from Angular.

Under the Angular src/app/api  you will now find the generated api module, models, services, and configuration file. Setting up new API module is as easy as including ApiModule in the app.module.ts imports. Now you can inject your newly generated HeroesService into any controller or other services that you'd like to make API calls from.

 

VSCode auto-completion using the generated Angular Service to get heroes

 

API Changes & Updating

APIs usually change over time and when the time comes that you need to update your API contracts, simply rerun the npm api command like previously done and any changes, both additions and deletions, will be reflected in the generated TypeScript. This is extremely valuable to teams because any API updates that break existing client-side code will become immediately apparent. Any data models that change because the API C# model changed will show up as an error when running the Angular CLI serve or build commands.

 

An error occurs in the case that the 'description' property is removed from the C# model and the npm api command is run again An error occurs in the case that the 'description' property is removed from the C# model and the npm api command is run again

 

References

Comments

Subscribe Here!