Search code examples
angularhttpswaggerdocumentation

Can I create a swagger or other API documentation from Angular Services?


I created an Angular app before creating a backend. Is there a service/npm package/library/etc I can use that scans the whole app services and its http requests and generate a swagger so the backend dev uses that?

I know there are some tools to do it the other way around (generate Angular Services out of a swagger) but I already have the code, I want to create the documentation for the endpoints I am using/expecting


Solution

  • compodoc should be able to to Generate json by following JSDoc annotations added to Angular service methods. https://compodoc.github.io/compodoc-demo-todomvc-angular/index.html which then can be fed to swagger.

    npm install -g @compodoc/compodoc

    Then configure compdoc

    {
      "title": "My Angular App API Documentation",
      "sourceDir": "src/app",
      "exportFormats": ["swagger"]
    }
    

    Annotate services

    import { HttpClient } from '@angular/common/http';
    import { Injectable } from '@angular/core';
    
    /**
     * A service for interacting with the My API.
     */
    @Injectable({
      providedIn: 'root'
    })
    export class MyApiService {
      /**
       * Retrieves the list of users.
       * @returns An observable that emits the list of users.
       */
      getUsers() {
        return this.http.get<User[]>('/api/users');
      }
    
      constructor(private http: HttpClient) { }
    }
    

    To generate swagger.json

    compodoc -p tsconfig.app.json
    

    Output file can be then given to BE guys?