Search⌘ K
AI Features

Create the GET Endpoint

Explore how to build GET endpoints in a NestJS RESTful API for an address book application. Learn to retrieve address data by ID using route parameters, parse inputs, and handle route matching order. Practice adding an endpoint to fetch all addresses while understanding NestJS routing mechanics.

Get address by using the id endpoint

We created the address module in previous lessons with a controller and service. It’s time to implement our first API endpoint!

Add the service method

First, let’s create a new method in AddressService.

TypeScript 4.9.5
@Injectable()
export class AddressService {
private addressDataStore: AddressDto[] = [];
// Retrieves an address by its unique ID.
getById(id: number) {
// Finds an address in the 'addresses' store
// where the 'id' property matches the provided 'id'.
return this.addressDataStore.find(t => t.id === id);
}
}

Here, we use the addressDataStore private property to store the address data. This is a temporary work-around, and we’ll implement the data persistent to the MySQL database later in the course.

Notice that the getById method doesn’t have a modifier in the code snippet above. We didn’t add a public modifier for the method because all class members default as public in TypeScript, which means they’re accessible from outside the class. ...