Skip to content

Define a practice exercise for students to bring together learning around APIs (Clients & Servers, Web Apps and HTTP, APIs, and Spring Boot)

License

Notifications You must be signed in to change notification settings

dazcodes/java-rest-api-exercise

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

46 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Java RESTful API Exercise: IOU Service

Description

Build a RESTful API service that allows users to create, read, update, and delete IOUs (I Owe You) using Java and Spring Boot.

Getting Started

Clone Repository

  • Fork this repository in your GitHub account
  • Clone your fork locally or open in CodeSpaces.
git clone [REPO_URL]
cd [REPO_NAME]

💡 Note: Replace [REPO_URL] with the link to your GitHub repository and [REPO_NAME] with the repository's name.

Create Database

  • Login to MySQL
mysql -u root -p

💡 Note: If your root user doesn't have a password set, omit the -p flag.

  • Create a new database and exit MySQL
CREATE DATABASE IF NOT EXISTS restapiexercise;
exit;

Initialise Project

  • Open this pre-configured Initializr project. Review the configured settings, but do not make any changes. Click "Generate" to download a zipped project.
  • Extract the downloaded zip file and copy the contents of the folder (not the folder itself!) to your local repository. Don't drag-and-drop in Explorer/Finder as there are hidden files which may not be correctly copied across.
    • macOS / Git Bash: cp -R [extracted directory]/. [local repo directory] e.g. cp -R ~/Downloads/restapiexercise/. ~/Dev/cbfacademy/java-rest-api-exercise (IMPORTANT: the /. after the extracted directory path is required for the command to work as intended)
    • Windows Command Prompt: xcopy [extracted directory] [local repo directory] /S /H /C /Y, e.g. xcopy C:\Users\myaccount\Downloads\restapiexercise C:\Dev\cbfacademy\java-rest-api-exercise /S /H /C /Y
  • Open your repository in VS Code
  • Add the following values to src/main/resources/application.properties:
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.open-in-view=true
spring.config.import=optional:./local.properties
  • In order to prevent sensitive values from being committed to version control, create a new file at src/main/resources/local.properties and add the following values:
spring.datasource.url=jdbc:mysql://localhost:3306/restapiexercise
spring.datasource.username=root # Replace "root" with your db user, if applicable
spring.datasource.password= # Specify your db user's password, if applicable

Install Dependencies

Open a terminal at the root of the repo directory and run the following command to install the dependencies:

macOS / Git Bash

./mvnw clean dependency:resolve

Windows Command Prompt

mvnw clean dependency:resolve

Run Application

To start the API from the terminal, run the following command:

macOS / Git Bash

./mvnw spring-boot:run

Windows Command Prompt

mvnw spring-boot:run

If successful, you should see output that ends similarly to the below

2024-04-12T11:49:59.055-04:00  INFO 39975 --- [REST API Exercise] [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path ''
2024-04-12T11:49:59.059-04:00  INFO 39975 --- [REST API Exercise] [           main] c.c.r.RestApiExerciseApplication         : Started RestApiExerciseApplication in 1.493 seconds (process running for 1.638)

Stop Application

Stop the application by pressing Ctrl + C

Exercise 1

  1. Create an ious package in the main restapiexercise package
  2. Create an IOU entity class that maps to the "ious" table and has the following fields:
    • UUID id
    • String borrower
    • String lender
    • BigDecimal amount
    • Instant dateTime
  3. Ensure the id field is set as the primary key and values are generated using the appropriate strategy
  4. Create getters and setters for each field, except id, which should only have a getter
  5. Create an IOURepository interface that extends ListCrudRepository<IOU, UUID>
  6. Ensure local.properties is correctly configured with your database details
  7. Start your API with ./mvnw clean spring-boot:run (if it's already running, restart it) and confirm there are no errors
  8. Check your database contains an "ious" table with the correct columns and data types

Exercise 2

  1. Create an IOUService class that accepts an IOURepository as a dependency and implements the following methods:
    • List<IOU> getAllIOUs()
    • IOU getIOU(UUID id) throws NoSuchElementException
    • IOU createIOU(IOU iou) throws IllegalArgumentException, OptimisticLockingFailureException
    • IOU updateIOU(UUID id, IOU updatedIOU) throws NoSuchElementException
    • void deleteIOU(UUID id)
  2. Create an IOUController class that implements the endpoints below. Ensure your service class is injected as a dependency and apply the appropriate annotations
  3. Start your API and confirm there are no errors
Method Endpoint Description
GET /api/ious Retrieve a list of (optionally filtered) IOUs
GET /api/ious/{id} Retrieve a specific IOU by its ID
POST /api/ious Create a new IOU
PUT /api/ious/{id} Update an existing IOU by ID
DELETE /api/ious/{id} Delete an IOU by ID

Exercise 3

  1. Create an ious package inside the test/java/com/cbfacademy/restapiexercise package
  2. Download the test suite and copy to the test ious package as IOUControllerTest.java
  3. Run the tests with ./mvnw test
  4. Examine the results. Which tests fail? What reasons are given?

Exercise 4

  1. Create a new API endpoint to return IOUs for a specific borrower:
    1. Create a method in your repository interface called findByBorrower that accepts a string borrower parameter.
    2. Create a method in your service class called getIOUsByBorrower.
    3. Extend the getIOUS method of your controller to accept an optional query string parameter, e.g.: getIOUs(@RequestParam(required = false) String borrower)
    4. Check the value of the borrower parameter to determine whether to call the existing service method or the new, filtered, one
  2. Test the modified endpoint
  3. Commit your changes

Exercise 5

  1. Create a new API endpoint to return IOUs with above-average value:
    1. Create a method in your repository interface called findHighValueIOUs.
    2. Define a native @Query annotation that will return all IOUs with an above average value. Hint: create a subquery using the AVG function
    3. Create a method in your service class called getHighValueIOUs.
    4. Create a getHighValueIOUS method in your controller, mapped to the /high path.
  2. Test the new endpoint
  3. Commit your changes
  4. Create a new endpoint at /low to return IOUs that are below or equal to the average value. Implement the repository method using JPQL instead of SQL

Testing the API

You can test your endpoints using Postman or your preferred REST client at http://localhost:8080/api/ious

The JSON representation of an IOU that you'll get in responses or provide in the request body for POST and PUT requests will resemble the following:

{
  "id": "d1415cfc-dbd9-4474-94fc-52e194e384fa",
  "borrower": "John Doe",
  "lender": "Alice Smith",
  "amount": 100.0,
  "dateTime": "2023-11-02T14:30:00Z"
}

💡 Note: Remember that the id property may not be needed for all request types.

Top Tips

  • 📸 Commit frequently and use meaningful commit messages. A granular, well-labelled history becomes an increasingly valuable asset over time.
  • 🌵 Use feature branches. Build the habit of isolating your changes for specific tasks and merging them into your default branch when complete.
  • 🚦 Use consistent naming conventions. Choose easily understandable names and naming patterns for your classes, functions and variables.
  • 📐 Keep your code tidy. Using the built-in formatting of VS Code or other IDEs makes your code easier to read and mistakes easier to spot.
  • 📚 Read the docs. Whether via Intellisense in your IDE, or browsing online documentation, build a clear understanding of the libraries your code leverages.
  • 📆 Don't wait until the last minute. Plan your work early and make the most of the time available to complete the assessment and avoid pre-deadline palpitations.
  • 🆘 Ask. 👏 For. 👏 Help! 👏 Your mentors, instructors and assistants are literally here to support you, so make use of them - don't sit and struggle in silence.

Best of luck! Remember, it's not just about the destination; it's the journey. Happy coding! 🚀

About

Define a practice exercise for students to bring together learning around APIs (Clients & Servers, Web Apps and HTTP, APIs, and Spring Boot)

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published