ng-openapi

website·Indexed 32 days ago

https://ng-openapi.dev

An Angular-first OpenAPI client generator that creates Angular services and TypeScript types from OpenAPI specifications. It includes a CLI for generation, support for multiple clients, runtime schema validation (e.g., using Zod), and a plugin system including the HttpResourcePlugin for reactive data loading and caching.

Tokens
20.8K
Snippets
103
Records
140
Agent score
48%

What's inside ng-openapi

  1. Overview of ng-openapi generated features

    The ng-openapi generator produces a complete API client layer including:

    • TypeScript Interfaces: Type definitions derived from OpenAPI schemas.
    • Angular Services: Injectable services utilizing Angular's dependency injection.
    • HTTP Interceptors: Built-in support for custom headers and automatic date transformation.
    • Provider Functions: Simplified setup via provideDefaultClient().
    • File Utilities: Helpers for handling files and downloads.
    • CLI Tool: A command-line interface that supports configuration files.
  2. Overview of ng-openapi

    ng-openapi is an open-source, Angular-first OpenAPI client generator. It is released under the MIT license and is designed to automate the creation of API clients for Angular applications based on OpenAPI specifications.
  3. Overview of the ng-openapi HTTP Resource Plugin

    The HTTP Resource plugin extends ng-openapi to generate services leveraging Angular's httpResource API instead of the traditional HttpClient. This approach provides built-in caching, loading states, error handling, and reactive updates powered by Angular Signals. It is currently optimized specifically for GET requests.
  4. Understand the ng-openapi generated output structure

    By default (with generateServices: true and dateType: "Date"), ng-openapi generates the following directory structure in the output folder:

    • models/: Contains TypeScript interfaces, enums, and unions. If modelFileStructure: 'per-type' is used, each schema gets its own file; otherwise, they are in index.ts.
    • services/: Contains one Angular service per controller/tag.
    • tokens/: Contains namespaced injection tokens for the client.
    • utils/: Contains helper utilities including base-interceptor.ts, date-transformer.ts (if dateType: "Date"), file-download.ts, and http-params-builder.ts.
    • providers.ts: Contains the provide<ClientName>Client() setup function.
    • index.ts: The main barrel export for the entire client.

    Plugins may add additional directories, such as validators/ (Zod plugin) or resources/ (HTTP Resource plugin).

  5. Use DateInterceptor or transformDates manually

    The DateInterceptor class and the transformDates utility function both accept a custom regular expression as an argument for manual setup or custom transformation logic.
    new DateInterceptor(/your-custom-regex/);
    transformDates(responseBody, /your-custom-regex/);
  6. Install and generate an Angular API client with ng-openapi

    ng-openapi is a client generator that creates type-safe Angular services and TypeScript interfaces from an OpenAPI specification. To get started, install the package as a development dependency and run the generator CLI pointing to your specification file and desired output directory.
    # Install ng-openapi
    npm install ng-openapi --save-dev
    
    # Generate from OpenAPI spec
    # -i: input specification file
    # -o: output directory
    ng-openapi -i swagger.json -o ./src/api
  7. Use the generated client provider in Angular application config

    When a clientName is specified in the configuration, the generator creates a provider named provide<ClientName>Client. This provider should be added to the app.config.ts file to initialize the client in the Angular application.
  8. Manually configure the OpenAPI client base path

    For complex scenarios requiring fine-grained control, you can manually configure the client by providing the base path token from the generated tokens/ directory. The token is named BASE_PATH_<CLIENTNAME> (e.g., BASE_PATH_PETSTORE). For the default client, BASE_PATH is a deprecated alias for BASE_PATH_DEFAULT.
    import { provideHttpClient } from "@angular/common/http";
    import { ApplicationConfig } from "@angular/core";
    import { BASE_PATH } from "./api/tokens";
    
    export const appConfig: ApplicationConfig = {
        providers: [
            provideHttpClient(), 
            { provide: BASE_PATH, useValue: "https://api.example.com" }
        ],
    };
  9. Manually register the DateInterceptor

    Because DateInterceptor is a class-based interceptor, it must be registered using the HTTP_INTERCEPTORS multi-provider. This requires the use of withInterceptorsFromDi() within provideHttpClient to ensure DI-based interceptors are processed.
    import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from "@angular/common/http";
    import { DateInterceptor } from "./client/utils/date-transformer";
    
    export const appConfig: ApplicationConfig = {
        providers: [
            provideHttpClient(withInterceptorsFromDi()),
            { provide: HTTP_INTERCEPTORS, useClass: DateInterceptor, multi: true },
        ],
    };
  10. Generate multiple API clients with ng-openapi

    To support multiple backend services, create separate GeneratorConfig files for each API. Each configuration should specify a unique clientName and a distinct output directory to avoid overwriting files. Use the -c flag with the ng-openapi CLI to generate each client individually.
    // users-api.config.ts
    import { GeneratorConfig } from "ng-openapi";
    
    const config: GeneratorConfig = {
        clientName: "Users",
        input: "./users-swagger.json",
        output: "./src/api/users",
        options: {
            dateType: "Date",
            enumStyle: "enum",
        },
    };
    
    export default config;
    ng-openapi -c users-api.config.ts
    ng-openapi -c orders-api.config.ts
  11. Download files in Angular using the downloadFileOperator

    The downloadFileOperator is an RxJS operator designed to handle file downloads in Angular applications. It should be used within a .pipe() chain on any Observable that emits Blob data. It triggers a browser download by creating a temporary URL and anchor element.
    import { Component, inject } from "@angular/core";
    import { downloadFileOperator } from "./api/utils/file-download";
    
    export class ReportComponent {
        private readonly reportService = inject(ReportService);
    
        downloadReport() {
            // Use the operator with the desired filename
            this.reportService.getReportById(123)
                .pipe(downloadFileOperator("report.pdf"))
                .subscribe();
        }
    }