File size: 1,833 Bytes
b4f755d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# Nestjs + fastapi

You can easily call this API from a NestJS microservice.

**.env**
```env
FASTAPI_BASE_URL=http://localhost:8000
SECRET_TOKEN=your_secret_token_here
```

**fastapi.service.ts**

```typescript
import { Injectable } from "@nestjs/common";
import { HttpService } from "@nestjs/axios";
import { ConfigService } from "@nestjs/config";
import { firstValueFrom } from "rxjs";

@Injectable()
export class FastAPIService {
  constructor(
    private http: HttpService,
    private config: ConfigService,
  ) {}

  async analyzeText(text: string) {
    const url = `${this.config.get("FASTAPI_BASE_URL")}/text/analyse`;
    const token = this.config.get("SECRET_TOKEN");

    const response = await firstValueFrom(
      this.http.post(
        url,
        { text },
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        },
      ),
    );

    return response.data;
  }
}
```

**app.module.ts**
```typescript
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { HttpModule } from "@nestjs/axios";
import { AppController } from "./app.controller";
import { FastAPIService } from "./fastapi.service";

@Module({
  imports: [ConfigModule.forRoot(), HttpModule],
  controllers: [AppController],
  providers: [FastAPIService],
})
export class AppModule {}
```

**app.controller.ts**
```typescript
import { Body, Controller, Post, Get } from '@nestjs/common';
import { FastAPIService } from './fastapi.service';

@Controller()
export class AppController {
  constructor(private readonly fastapiService: FastAPIService) {}

  @Post('analyze-text')
  async callFastAPI(@Body('text') text: string) {
    return this.fastapiService.analyzeText(text);
  }

  @Get()
  getHello(): string {
    return 'NestJS is connected to FastAPI';
  }
}
```