linfini
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Swagger in NestJS Project ![image](https://hackmd.io/_uploads/SJbG-ZSJbe.png) In a [blog](https://hackmd.io/@linfini/husky-and-lintstaged) I wrote earlier, I mentioned tools that once used, I don't want to go back and I would like to add one more to the list. Yes :smile: you can see from the banner, it's Swagger! ### I. Why Swagger It's probably the most popular name you'll hear when it comes to API documentation and generation. Since TypeScript has become almost mandatory for front-end development, I find it hard to have to manually create type for API response and Request, especially in a complex project. ### II. Swagger in NestJS I first used Swagger in a Java Springboot project, where we define everything in a YAML file first, then generate DTOs for both frontend and backend. You can check out how to structure the Swagger doc [here](https://hackmd.io/@linfini/write-rest-docs-with-swagger). But with NestJS, we do the opposite, which is defining DTOs and entities first and then generating API docs for frontend. ### III. How to implement #### 1 - Installation We first install the required dependency. ```javascript! npm install --save @nestjs/swagger ``` Then we initialize Swagger using the `SwaggerModule` class ```javascript! // main.ts import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; // Swagger config const config = new DocumentBuilder() .setTitle('My API') .setDescription('Auto-generated OpenAPI spec') .setVersion('1.0') .build(); const document = SwaggerModule.createDocument(app, config); // Serve Swagger UI SwaggerModule.setup('api/docs', app, document); // write spec file writeFileSync('swagger/openapi-spec.json', JSON.stringify(document, null, 2)); ``` So, what we’re doing is simply integrating Swagger into your app. When you develop the app locally (let’s say it’s running on port 8080), you can access the API documentation at `http://localhost:8080/api/docs`. <img src="https://hackmd.io/_uploads/SkhqU6NkWg.png" alt="swagger_doc" style="border: 1px solid black"> In the official documentation, you won’t find the `writeFileSync` function, but I’ve included it here because we’re attempting to create the document file that the frontend can use to generate and utilize the type. You can also download this document as JSON manually by adding `jsonDocumentUrl` in swagger setup. Then the JSON file will be exposed in `http://localhost:8080/swagger/json` ```javascript! SwaggerModule.setup('api/docs', app, document, { jsonDocumentUrl: 'swagger/json', }); ``` <img src="https://hackmd.io/_uploads/ByhVe04ybg.png" alt="swagger_json" style="border: 1px solid black"> *And here’s a simple tip: all API endpoints should have the same tag unless your app is exceptionally complex. Otherwise, it would be a hassle for the frontend because we would need to set up a separate configuration for each level 1 endpoint.* #### 2 - Generate document for frontend usage With the provided JSON file, frontend developers can generate the types themselves. However, with a bit of additional setup, they can do so more easily. To achieve this, create a shell script in the same folder as the JSON file. Whenever you want to generate the document, simply run the script. ```shell! #!/bin/bash set -e npx openapi-generator-cli generate \ -i openapi-spec.json \ -g typescript-axios \ -o ./output echo "Frontend client generated in swagger/output/" ``` #### 3 - It's all about decorator The reason I say this is that all we need to do is add decorators to any controllers and DTOs we want to expose. All the available OpenAPI decorators have an `Api` prefix to differentiate them from the core decorators. However, I won’t mention all of them; I’ll only mention those I use the most, which can create sufficient documents for both the front and back end. Each decorator has a designated level at which it may be applied. You can refer to the full list for more information [here](https://docs.nestjs.com/openapi/decorators). **@ApiTags('Default')** This decorator should be added to the top of all your controllers so that all API endpoints can be set up simultaneously on the frontend. As I mentioned earlier, if you want the frontend to set up differently for each endpoint, you can ignore this decorator. **@ApiOperation({ operationId: 'getRecipes', summary: 'Get recipes'})** This decorator will indicate the API function that the frontend will call, as shown below. At the very least, declare `operationId`. Otherwise, the API function name will be automatically generated and will be long and not very intuitive. ![image](https://hackmd.io/_uploads/ByfXzyrkbl.png) **@ApiResponse({status: 200, description: 'Get recipes', type: RecipeListResponseDto})** This decorator is essential for generating the type of the API response. Since an error will be thrown, we don’t need to specify the error response. Make sure to clarify the type, or it will be meaningless. **@ApiParam** & **@ApiQuery** We don’t need to define this since Swagger scans everything automatically. If your API has queries and parameters, they will be included in the Swagger documentation. I’m not sure why, but when working on my own project, even when queries are optional, the type is still generated as required. So, if you encounter the same issue, simply add this decorator to specify that the query is optional. ```javascript! @ApiQuery({ name: 'name', required: false }) ``` **@ApiProperty()** For defining additional information or a specific property of a Data Transfer Object (DTO), use this decorator. Typically, we don’t need to use this decorator if we name our file with the correct suffix `.dto.ts`. Swagger can scan it and it will be generated as is. I usually include examples for the properties of my DTOs to make my document more meaningful for others. ```javascript! @ApiProperty({ example: '1' }) id: string; ``` With just a few decorators like these, we can enhance our API document by adding more details and making it easier for frontend developers to generate a usable type. For document generation, you can use the open API CLI. Please take your time to check out their [rules](https://docs.nestjs.com/openapi/cli-plugin). ### IV. Conclusion I’m writing this to share my implementation of Swagger in NestJS. However, if you have a more efficient way to achieve this, please comment and let me know. For more details, you can refer to the [official document](https://docs.nestjs.com/openapi/introduction).

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully