zijianhuang / webapiclientgen

Strongly Typed Client API Generators generate strongly typed client APIs in C# .NET and in TypeScript for jQuery and Angular 2+ from ASP.NET Web API and .NET Core Web API
MIT License
167 stars 38 forks source link
ajax android angular angular2 asp-net aurelia axios blazor-webassembly codedom csharp dotnet fetch-api jquery restful typescript typescript-codedom web-api webapi xamarin

Strongly Typed Client Web API Generators generate client API codes in C# and TypeScript from ASP.NET (Core) Web API directly without involving Swagger/OpenAPI or Swashbuckle, therefore maximizing the support for data types of your Code First approach of ASP.NET Web API.

Products

This project delivers these products:

  1. Code generator for strongly typed client API in C# supporting .NET and Xamarin.Forms.
  2. Code generators for strongly typed client API in TypeScript for jQuery, Angular 2+, Aurelia, Axios and Fetch API.
  3. TypeScript CodeDOM, a .NET CodeDOM component for TypeScript for developing TypeScript code generators.
  4. POCO2TS.exe, a command line program that generates TypeScript interfaces from POCO classes.
  5. Fonlow.Poco2Ts, a component that generates TypeScript interfaces from POCO classes.
  6. Plugins for jQuery, AXIOS, Fetch API, Aurelia, Angular 2+ as well as Angular Typed Reactive Forms.
  7. Fonlow.DataOnlyExtensions with JSON converters for handling date only scenarios between the clients and server which sit in different timezones. A .NET Framework package is also available.

Packages

Use Cases and Downloads

The products are released mostly through NuGet.

  1. Generate C# client API, then use package Fonlow.WebApiClientGenCore
  2. Generate TypeScript client API, then use one of the plugins of Fonlow.WebApiClientGenCore:
    1. jQuery and HttpClient helper library
    2. Angular 6+
    3. Angular 6+, plus FormGroup creation for Reactive Forms with Description
    4. AXIOS
    5. Aurelia
    6. Fetch API
  3. Develop TypeScript code generator through the CodeDOM approach, then use package Fonlow.TypeScriptCodeDOMCore.
  4. Develop TypeScript code generator through the CodeDOM approach for POCO and more, then use package Fonlow.Poco2TSCore , or use PowerShell 7 scripts.
  5. Generate TypeScript type interfaces, then use Poco2TSCore.exe, a console app.
  6. Develop a feature that reads XML document of an .NET assembly, then use package Fonlow.DocCommentCore.

Hints:

Remarks:

Key Features

  1. Client API codes generated are directly mapped from the Web API controller methods, .NET primitive types and POCO classes. This is similar to what svcutil.exe in WCF has offered.
  2. Doc comments of controller methods and POCO classes are copied.
  3. Some validation attributes are used to generate doc comments for TypeScript codes.

Key Benefits for Developer Experience

  1. WebApiClientGen is seamlessly integrated with ASP.NET Core Web API with very little steps/overheads to setup, maintain and synchronize between Web API and client APIs, during RAD or Agile Software Development.
  2. Support all .NET primitive types including decimal.
  3. Support DataTime, DataTimeOffset, DateOnly, Array, Tuple, Dynamic Object, Dictionary and KeyValuePair
  4. Strongly typed generated codes are subject to design time type checking and compile time type checking.
  5. Provide high level of abstraction, shielding application developers from repetitive technical details of RESTful practices and traditional codes of AJAX calls.
  6. Rich meta info including doc comments make IDE intellisense more helpful, so application developers have less need of reading separated API documents.
  7. Generated doc comments based on .NET validation attributes.
  8. Generated doc comments based on numeric types, DateOnly and GUID for TypeScript codes.
  9. Generated TypeScript codes conform to the TypeScript strict mode, and the generated Angular 2+ codes conform to the Angular strict mode.

Examples

  1. POCO classes
  2. Web API
  3. Generated client API C# codes
  4. Client codes using the generated library in C#
  5. Generated client data models and API in TypeScript for jQuery, for Angular 2, for Aurelia and for Axios
  6. Client codes using the generated library in TypeScript
  7. Online Demo with Angular Heroes hosted in GitHub.IO talking to a real backend

Remarks:

  1. JavaScript codes compiled from generated TypeScript codes could be used in JS applications, however, obviously no type info will be available, while application programmers may still enjoy intellisense and abstraction from AJAX details.
    1. React and Vue.js applications typically use Axios or Fetch API for HTTP requests. Since June 2019, babel has supported namespaces thanks to this pull request, so you should be able to do React TSX programming with generated TypeScript codes.

Concepts

  1. Web API vendors / developers should provide client API libraries to developers of client programs, as Google and Amazon etc. would do in order to make the RESTful Web API reach wider consumers (internal and external) efficiently.
  2. To client developers, classic function prototypes like ReturnType DoSomething(Type1 t1, Type2 t2 ...) is the API function, and the rest is the technical implementation details of transportation: TCP/IP, HTTP, SOAP, resource-oriented, CRUD-based URIs, RESTful, XML and JSON etc. The function prototype and a piece of API document should be good enough for calling the API function.
  3. The better you have separation of concerns in your Web API design, the more you will benefit from the components of this project in order to deliver business values sooner, with less handcrafted codes , less repetitive tasks and less chances of human mistakes.

Expected Programming Practices

Strongly Typed Function Prototype

ReturnType DoSomething(Type1 t1, Type2 t2 ...)

        [HttpGet]
        [Route("getPerson/{id}")]
        public Person GetPerson(long id)

Model Validation through Middleware

Rather than writing explicit codes of validating the request payload, it is expected that you use middleware to validate. For example:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers(
        options =>
        {
            options.Filters.Add(new ValidateModelAttribute()); // wholesale style to check model binding for all API calls.

References:

Model Validation through ApiControllerAttribute

For example:

    [ApiController]
    [Route("api/[controller]")]
    public class HeroesController : ControllerBase
    {

Non-2xx HTTP Status Codes Handled by Middleware, optional

Even if you explicitly write codes in an API function to handle exceptions and return non-2xx HTTP status code, you should have a safty net of catching uncaught exceptions and return HTTP status codes.

References:

Prerequisites

Server side:

  1. .NET 7/8
  2. Add CodeGenController.
  3. In the service startup codes, add the following:
    services.AddControllers(
    options =>
    {
    #if DEBUG
        options.Conventions.Add(new Fonlow.CodeDom.Web.ApiExplorerVisibilityEnabledConvention());
    #endif
    }
    )

Remarks:

.NET client side:

  1. .NET Framework 4.5.2, or Universal Windows, or Mono.Android, or Xamarin.iOS, or .NET Core 2.0/2.1/3 and .NET 5
  2. ASP.NET Web API 2.2 Client Libraries
  3. Json.NET of Newtonsoft for Content-Type application/json
  4. Microsoft Build Tools 2015

NewtonSoft.Json or System.Text.Json

As of .NET 7, for serialization System.Text.Json reassembles over 95% of NewtonSoft.Json. There are only a few edge cases of complex POCO structures that System.Text.Json can not handle.

WebApiClientGen supports both on server side and C# client side. For C# clients, you may use "UseSystemTextJson" in the codegen settings.

Nevertheless, if your application involves complex POCO structures, using NewtonSoft.Json is a safe bet as of .NET 7.

TypeScript client side:

  1. TypeScript compiler
  2. jQuery
  3. Angular 2-17
  4. Aurelia
  5. Axios
  6. Fetch API

For more details, please check:

  1. WIKI
  2. Settings Explained
  3. Generate C# .NET Client API for ASP.NET Web API
  4. Generate TypeScript Client API for ASP.NET Web API
  5. ASP.NET Web API, Angular2, TypeScript and WebApiClientGen
  6. Generate C# Client API for ASP.NET Core Web API
  7. Intended Solutions for Intentional Limitations of Strongly Typed OpenAPI Client Generators. The article is just using OpenApiClientGen as an example, while the principles and solutions can be applied to generated codes by WebApiClientGen for your client apps.
  8. DateOnly in ASP.NET Core 6

Demo Applications

The Demo applications in this repository are mainly for testing WebApiClientGen during development. And there are other demo applications in the following repositories, demostrating how real world applications could utilize WebApiClientGen:

  1. WebApiClientGen Examples for .NET Framework, .NET Standard, Xamarin, and vue TS.
  2. .NET Core Demo for ASP.NET Core MVC, Web API, ASP.NET Core + Angular, MAUI, fetchAPI, vue TS and React TS.
  3. WebApiClientGen vs Swagger

These demo applications are actively maintained and kept up-to-date with the latest frameworks. If you are still staying with some older frameworks like Angular 4 or 5 or .NET Core 2.0, you may navigate to respective tags of the repositories and checkout.

Tour of Heroes

Tour of Heroes is the official Angular tutorial demo app.

To illustrate the programmer experience of using WebApiClientGen, the following demo apps are crafted with similar architectural design for the same functional features on various development frameworks or libraries, however, talking to a real backend.

  1. Angular 2+, and Typed Reactive Forms
  2. Xamarin
  3. MAUI. Migrated from Xamarin Heroes.
  4. Aurelia. Integration test suite included.
  5. React. Integration test suite included.
  6. Blazor Standalone

NewtonSoft.Json or System.Text.Json

While WebApiClientGen supports both, however, the primary support has shifted to System.Text.Json since 2024.

NewtonSoft.Json still have a few advantages upon certain scenarios and contexts:

  1. If you have a lot POCO classes decorated by DataContractAttributes, because of supporting legacy apps, or supporting both XML and JSON serialization, NewtonSoft.Json gives you inherent support, while System.Text.Json provides some troublesome and indirect support since .NET 7.
  2. For some array types and dynamic, NewtonSoft.Json is still better.