0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Nest.jsでRestAPI① HelloWorld

Posted at

Nest.jsでRestAPIを実装していくシリーズ1回目。
今回は環境構築からNest.jsプロジェクトを作成してHelloWorldするところまで。
作成したプロジェクトの中身もざっくり解説するよ。

環境

  • Windows10
  • Node.js:22.17.0
  • Nest.js:11.0.7

インストール

Node.jsをインストール

  1. 公式からインストーラをダウンロードして実行
  2. インストールされたことを確認
    PS D:\> node -v
    v22.17.0
    PS D:\> npm -v
    10.9.2
    

Nest.jsをインストール

  1. インストールコマンド実行
    PS D:\> npm i -g @nestjs/cli
    
    added 248 packages in 17s
    
    45 packages are looking for funding
      run `npm fund` for details
    
  2. インストールされたことを確認
    PS D:\> nest -v
    11.0.7
    

プロジェクトを作成して起動

  1. 任意のディレクトリでnest new プロジェクト名で新規プロジェクト作成。
    今回はnpmを使用するよ。
    PS D:\> nest new sample-project
    ✨  We will scaffold your app in a few seconds..
    
    ✔ Which package manager would you ❤️  to use? npm
    CREATE sample-project/.prettierrc (54 bytes)
    CREATE sample-project/eslint.config.mjs (869 bytes)
    CREATE sample-project/nest-cli.json (179 bytes)
    CREATE sample-project/package.json (2113 bytes)
    CREATE sample-project/README.md (5126 bytes)
    CREATE sample-project/tsconfig.build.json (101 bytes)
    CREATE sample-project/tsconfig.json (565 bytes)
    CREATE sample-project/src/app.controller.ts (286 bytes)
    CREATE sample-project/src/app.module.ts (259 bytes)
    CREATE sample-project/src/app.service.ts (150 bytes)
    CREATE sample-project/src/main.ts (236 bytes)
    CREATE sample-project/src/app.controller.spec.ts (639 bytes)
    CREATE sample-project/test/jest-e2e.json (192 bytes)
    CREATE sample-project/test/app.e2e-spec.ts (699 bytes)
    
    ✔ Installation in progress... ☕
    
    🚀  Successfully created project sample-project
    👉  Get started with the following commands:
    
    $ cd sample-project
    $ npm run start
    
    
                              Thanks for installing Nest 🙏
                     Please consider donating to our open collective
                            to help us maintain this package.
    
    
                   🍷  Donate: https://opencollective.com/nest
    
    
  2. 出てきたメッセージの通り、プロジェクトディレクトリに移動して、起動する。
    PS D:\> cd sample-project
    PS D:\sample-project> npm run start
    
    > sample-project@0.0.1 start
    > nest start
    
    [Nest] 15688  - 2025/07/05 5:55:00     LOG [NestFactory] Starting Nest application...
    [Nest] 15688  - 2025/07/05 5:55:00     LOG [InstanceLoader] AppModule dependencies initialized +19ms
    [Nest] 15688  - 2025/07/05 5:55:00     LOG [RoutesResolver] AppController {/}: +7ms
    [Nest] 15688  - 2025/07/05 5:55:00     LOG [RouterExplorer] Mapped {/, GET} route +3ms
    [Nest] 15688  - 2025/07/05 5:55:00     LOG [NestApplication] Nest application successfully started +2ms
    
    Nest application successfully startedと表示されればOK。
    停止したい時はCtrl+C
  3. http://localhost:3000/ にアクセスすると、「Hello World!」と返ってくる。
    APIを作っていくのでPostmanを使用すると良いかも。
    image.png

ソースコード本体(srcディレクトリ)について

作成直後は

  • main.ts
  • app.module.ts
  • app.controller.ts
  • app.service.ts
  • app.controller.spec.ts

が存在するはず。

main.ts

アプリケーションのエントリファイル。Nestアプリケーションインスタンスを生成する。

app.module.ts

ルートモジュールファイル。Nest.jsは機能ごとにモジュールを作成していくが、そのルートとなるモジュール。

app.controller.ts

ルーティングを行うファイル。
例えば、以下のように変更すると、http://localhost:3000/api/hello にリクエストできるようになる。

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller('api') // 変更
export class AppController {
  constructor(private readonly appService: AppService) {} // サービスクラスをDI

  @Get('hello') // 変更
  getHello(): string {
    return this.appService.getHello(); // サービスクラスの戻り値をそのまま返す
  }
}

app.service.ts

ビジネスロジックを担うサービスクラスのファイル。
コントローラーでこのクラスの戻り値をそのまま返しているので、戻り値を変えてみる。
オブジェクトを返せば、JSONをレスポンスとして返すことができる。

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): object {
    return {
      message: 'HelloWorld!',
    };
  }
}

image.png

app.controller.spec.ts

コントローラーのユニットテスト。
これで実行できる。

PS D:\sample-project> npx jest src/app.controller.spec.ts
 PASS  src/app.controller.spec.ts
  AppController
    root
      √ should return "Hello World!" (18 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.363 s
Ran all test suites matching /src\\app.controller.spec.ts/i.

個人的にsrcの中にテストファイルがあるのは気持ち悪いので、srcと同階層にあるtestの中にぶち込んでる。
今回は特にいじらない。

まとめ

以上、Nest.jsのHelloWorldでした。
次回は新規モジュールを作成する予定。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?