---
# System prepended metadata

title: 1Building your First RESTful CRUD API.

---

# 1Building your First RESTful CRUD API.
## Part 1: Getting set up and creating an entity object

This is a guide to help you get build your first RESTful CRUD API using Java Spring Boot. You will be introduced to libraries such as Spring Web, Lombok, Java Persistence API(JPA) and H2 (an in-memory database) to get you up and running as quickly as possible.
This guide is split into a few different parts:
1. Introduction to the project
2.  creating an entity object
3. Creating the repository layer
4. Creating the domain object
5. Creating the service layer
6. Creating the controller layer

## What are we building and how can we interact with it?
We are going to build a **Reservation Management Service** (RMS).The RMS should have the following functionality and the client should be able to interact with the service using the following endpoints:
- Create a new reservation
    - POST `http://localhost:8080/api/v1/reservation`
- Retrieve details about the customer’s upcoming reservation
    - GET `http://localhost:8080/api/v1/reservation/{reservationId}`
- Update the customer’s reservation
    - PUT `http://localhost:8080/api/v1/reservation/{reservationId}`
- Delete the customer’s reservation
    - DELETE`http://localhost:8080/api/v1/reservation/{reservationId}`

Any client should be able to hit these various endpoints to perfrom the actions that the service is capable of. 
## Architecture overview



# CAN WE GET STARTED ALREADY!? Damn..
## Step 1: Create the RMS Spring Boot project. 
Go to  [http://start.spring.io/](https://start.spring.io/) 
![](https://i.imgur.com/Bf8vV9k.png)

You can either create a new Spring Boot project using the Spring Initializr, or you can clone my repository to obtain the starter files (clone the repo and checkout branch [part-1-starter-files](https://github.com/csapty12/restaurantManagementSystem/tree/part-1-starter-files))
- *Project type* - Gradle
- *Language* - java
- *Spring Boot version* - 2.4.1 (use the lastest LTS version of Spring Boot)
- *group ID* - com.rms
- *Artifact ID* - reservationservice
- *Service Name* - reservationservice
- *Package name* - com.rms.reservationservice
- *packaging* - WAR  (this will be covered later. TLDR; as we are building a web app, we will eventually want to deploy this to a web server like Tomcat) 
- *Starter Dependencies* - 
	- **Spring Web**
	- **Lombok** - a annotation rich library that helps remove more boilerplate code
	- **Spring Data JPA**
	- **H2**
## The Project Structure
When you first import the project, there will already some folders and files created for you including:
- ***bin*** - where your compiled code will be placed, as well as your WAR file when it is generated
- ***gradle*** - enables us to use gradle commands without needing to install gradle on our local machines. 
- ***src/main***- where all our application code and application configuration will live (more on this next). 
- ***src/test*** - where all our automated tests for the API will live. 
- ***build.gradle*** - where we plugin our dependencies so that we do not need to install the library JAR's ourselves.
- README.md - the readme for your project. 
We will dive deeper into these various files and directories through out the guide, to help you get to grips with their purposes, but for the time being, lets start building our Reservation Management Service!

### The build.gradle file:
We will not be using this file much, however it is quite an important file as this is where dependencies will be imported from. This way, we can simply tell gradle to manage our dependencies for us so that we do not have to. Your buildd.radle file should look something like this:
```
plugins {
	id 'org.springframework.boot' version '2.4.1'
	id 'io.spring.dependency-management' version '1.0.10.RELEASE'
	id 'java'
	id 'war'
}

group = 'com.rms'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

configurations {
	compileOnly {
		extendsFrom annotationProcessor
	}
}

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	compileOnly 'org.projectlombok:lombok'
	runtimeOnly 'com.h2database:h2'
	annotationProcessor 'org.projectlombok:lombok'
	providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
	useJUnitPlatform()
}

```
Notice that in the dependencies section, we can see that `spring-boot-starter-data-jpa`, `spring-boot-starter-web`, `lombok`, and `h2` are being used, as these are what we selected at project initialisation. These dependencies pull in multiple libraries so that we can get going with what really matters - building the RMS. 

## Time to start coding - But where to begin?
We have been told that for a customer to make a reservation, they need to provide the following data to the service which we need to store in our database:
- A unique ID to identify the reservation
- First Name
- Last Name
- Number of Guests
- Reservation Date
- Reservation Time

To begin with, lets create a representation of this information in our code which will be stored in the database.

- [ ] Create a new package called `entity` within  `src/main/java/com/rms/reservationservice`. 
- [ ] Create a class called `ReservationEntity`. Within this class we can represent what our reservation data will look like. 
- ***Entity*** - an object representation of an item of a table in a database, also known as a **Data Access Object (DAO)**. The Entity may contain certain "metadata" fields that relate to the object being stored in the database, that the rest of the application does not necessarily need to know about e.g. createdAt, or updatedAt fields. An entity's only purpose is to make interactions with the database and thats it.We should not have any custom business logic within our entities. 

```
package com.rms.reservationservice.entity;

import lombok.*;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDateTime;

@NoArgsConstructor(access = AccessLevel.PROTECTED)
@AllArgsConstructor
@Data
@Builder
@Entity
@Table(name = "reservation")
public class ReservationEntity {

    @Id
    private String id;
    private String firstName;
    private String lastName;
    private LocalDateTime reservationTime;
    private int numberOfGuests;

}
```
The `ReservationEntity` class makes use of multiple annotations, to reduce the amount of boilerplate code that needs to be written. 

- ***@NoArgsConstructor(access = AccessLevel.PROTECTED)*** - exists only for JPA, we are not going to be using this ourselves, but JPA requires it be there.
- ***@AllArgsConstructor*** - Gives us the option of creating ReservationEntity objects via a constrcutor call to be saved into the database.
- ***@Data*** - provides out of the box methods such as getters, setters, toString, EqualsAndHashCode (see more [here](https://projectlombok.org/features/Data)).
- ***@Builder*** - Enables you to use the builder design pattern to create immutable objects in a slightly more verbose manner.
- ***@Table(name=‘reservation’)*** - Specifies the details of the table that will be used to persist the entity in the database. In this case, we are able to override the name of the table to be `reservation`.
- ***@Entity*** - Indicates that this is a JPA entity, that will represent a row of the "reservation" table in the database. 
- ***@Id*** - Indicates to JPA that this is the `ReservationEntity`'s primary key, which is something that we will generate later.


***Note on the @Entity annotation*** - When we save an object in the database, we use an Object Relational Mapper (ORM) such as Hibernate to handle the mapping from an object to a relational database for us so we don’t have to. The Spring Data JPA starter dependency that we selected when creating the project provides the hibernate implementation for us! EVEN LESS BOILERPLATE CODE!

By using these annotation, we are now ready to connect to a database and see the tables being created.
If you did get stuck, please checkout the branch [part-1-creating-reservation-entity](https://github.com/csapty12/restaurantManagementSystem/tree/part-1-creating-reservation-entity) and compare your code against mine.
In [Part 2: Creating the Repository Layer](https://hackmd.io/@csapty12/rJ7KwA_Cv), we are going to start to interact with a database by creating the repository layer and configuring the H2 database. See you there!