4.55 out of 5
4.55
422 reviews on Udemy

Practical Java : Spring Boot 3 REST API with Elasticsearch 8

Java (Spring Boot 3), REST API, Elasticsearch, Kibana, Github to develop & monitor back-end applications
Instructor:
Timotius Pamungkas
5,164 students enrolled
English
Various tricks offered by Spring to ease your programming effort
Practical Knowledge of Spring Boot : REST API, Unit test
Document your REST API and keep your source code sync with documentation
Learn the basic of source code version control
Understand basic usage of Elasticsearch & Kibana, and how to integrate java code with them
Create basic data visualization & dashboard using Elastic search & Kibana

New Update on July 2023

  • Updated to Elasticsearch 8.x and Spring Boot 3.x

  • Updated all videos with better audio

As a developer, we need to work productively. In Java programming, one way to achieve this is by Using Spring Framework. Recognized as one of the popular framework in Java world, Spring will increase developer productivity a lot. It has wide arrays of technology that can be used on almost any enterprise use-cases.

This course is suitable for you, if you already write codes (especially Java) for some times, and want to know new things, that relevant to today’s job demand. Or you just tech savvy that want to sharpen your Java programming skills to get more advanced level. In some of companies, you might have been work with legacy Java systems that already 5 years old or more. In that case, this course is suitable to refresh your mind, keep updated and get ready to adapt to new technology.

You don’t have to be advanced Java programmer to learn this course, although some basic Java programming is required. I will teach you step by step, started from little theory to give you some clarity, and most of the times we will do practical hand-codes, or using tech-related-tools.

What Will You Learn?

In this course, we will use following technologies

  • Java

  • Spring & Spring Boot

  • Eclipse & Spring Tools Suite

  • Gradle

  • Postman

  • Elasticsearch

  • Spring Data for Elasticsearch

  • Git & Github

  • Logging with logback

  • Automatic API documentation with Swagger

You will get introduction and practical lesson how to using them during your journey as Java developer.

Note for Non-Windows Users

I’m very sorry, but currently I don’t have Mac or Linux environment, so I can’t show you step-by-step video to install our tools in environment other than Windows. You can find step-by step installation guide on each product’s page but currently not in this course. However, the content of the course is applicable for any operating system.

What “Practical” Means?

As the title says, we will learn practical things about Java, especially Spring Framework. This course’s purpose is preparing you to be ready to handle  real-life applications. Of course, real-life applications has a lot more complexity and a lot more difficult that what we will learn in this course. Java framework itself has been around for 20 years, with Spring Framework has been live since 2003. With such long history, it is impossible to tell everything in just one course. This course is to preparing you to take the first few steps for begin journey as advanced Java developer, particularly using Spring Framework.

In this course, you will get several hand-on code, and tips for best-practice in REST API programming with Spring Boot.

Is This Course Suitable for You?

To answer this, please see the preview video on section 1.

If you have basic understanding of Java, and eager to learn, then this course is suitable for you. But if you are a seasoned Java developer that constantly update your knowledge, you might even smarter then me, and this course might be too easy for you.

Please check the course content to find out if this course can meet your expectation.

You Get Involved in This Course

Being a programmer need discipline and persistence. You need to learn. You will get errors, fix, and improve it -again and again- until you become good. This course will give you some quizzes and coding exercises, where you can get involved, and practice what you have learned. Of course, not all of you happy with this approach. So I design the quiz and coding exercises to be optional. Work with them if you like, or straight to the answers and practice directly.

Why Choose Me as Your Instructor?

— Experience —

I have been developing Java apps for enterprise since early 2010, from old-style JSP & JDBC, up to Spring framework which is currently most popular Java framework. Based on real-life experience, I know what should be done to create program that not just functionally runs, but also technically good. I experience programmers pain point, or operation team pain point and how to handle them.

I have been lead team as Engineering Manager & Architect for several years, and as a part of responsibility, coaching and teaching tech skills also part of my job. So I can deliver good lectures, based on real-life experience on Java programming.

— Serious —

I became instructor not for social purpose, but to earn some money. Thus, you are my customers, and I try my best not to disappoint you. I will try to give best value for you, so you feel happy spend your money, and take another of my course. I will try to answer your question, as long as it still in this course’s scope.

Elasticsearch & Kibana for Java Developers

In this course, I will introduce you to technology that maybe you’re not familiar with: Elastic search & Kibana.

These two technologies are quite popular. Knowing those two things will be an added value for every developer. Elasticsearch is commonly used as search engine because it is very fast. We will learn basic data manipulation with Spring Data Elasticsearch.

We will also learn about Kibana, an open source tools to visualize data (example : create real-time chart) and creating dashboard from several charts.

API Unit Testing & Documentation

You will learn how to write unit testing. That is a source code to test source code. We can do unit testing for repetitive test tasks, and helping make sure that no broken code due to some changes.

Also, in this course we will learn how to create API documentation with almost no effort, because we will use library to help us create API documentation automatically. The API documentation output are: HTML, or JSON format that can be transferred to more sophisticated API documentation tools.

Full English Subtitle

This course comes with perfect English subtitle. I myself not a native English speaker, so to give better experience for students (you), I provides accurate English subtitle for all lectures.

This course is safe!

This course comes with a 30 day money-back guarantee. That means if you are not satisfied with this course, just let me know and I’ll give your money back 100%. So no risk at your side for taking this Java course. You can be equip yourself with knowledge for real-world: Java, Spring, database, version control with github, REST API, and many more. You can go on, develop good enterprise or start-up software, potentially make an awesome career (and money) for yourself. Or you get your money back if you don’t like it.

Of course, you can see some preview course, all for FREE. Just find out the course content marked as Preview and play the video. No credit card required, no question asked, just play the video.

Road to Microservice

REST API is one important pillar of microservice architecture. In micro service, we use REST API and asynchronous messaging for inter-service communication. Services communicating by exchanging messages over REST API, or messaging channels like RabbitMQ.

In this course, you will learn the theory and hand-code of messaging with REST API your one step ahead toward modern micro service architecture.

Introduction

1
Welcome!
2
Before You Start : Reccomendation and Tips
3
Course Structure
4
Technology In This Course

This course covers various technologies that will be used throughout. It introduces Java as a programming language, highlighting its longevity and frequent updates. The Spring framework is discussed, emphasizing its ability to increase productivity and reduce boilerplate code. Eclipse is recommended as an integrated development environment (IDE) for Java development, while Gradle is suggested as a build automation tool and dependency management system. The use of Google Chrome as a web browser, specifically for accessing APIs and viewing JSON data, is mentioned. Postman is introduced as a development environment for APIs, offering features for execution, testing, and documentation. Elasticsearch is suggested as a data storage solution, optimized for search and analytics. Version control using Git is emphasized as a crucial tool for collaboration among developers, with GitHub mentioned as a cloud-based repository for source code. Docker, a popular container technology, is also mentioned as an optional tool for easy installation and running of various technologies.

Installation

1
Download Links
2
Installation (Windows)

This lecture provides comprehensive guidance on downloading and installing the essential tools required for Java development with Spring. It covers the installation process for various tools such as Java, Eclipse IDE, Spring Tools Suite, Postman, Git, Elasticsearch, and Kibana. Detailed instructions are provided for each installation step, including setting up environment variables and verifying the installations.

REST API & JSON

1
REST API Basic Concept

REST API is a crucial tool for connecting applications and facilitating information sharing. It acts as a user interface for applications, allowing them to interact with each other. APIs provide functionality to other applications without exposing internal code. They are language and platform-independent, making them versatile. REST API, based on the REST architectural style, is a widely used standard for web APIs. It follows principles such as a uniform interface, client-server architecture, and statelessness. REST APIs use HTTP protocol and JSON for communication. They offer a secure and efficient way to exchange data and access functionalities.

2
JSON Overview

JSON, or JavaScript Object Notation, is a widely used data format in modern applications based on REST. It represents data in name-value pairs and sometimes includes arrays. JSON is language-independent and uses readable text format. It allows for easy parsing and creation in most programming languages. JSON enables REST API independence, allowing API providers and consumers to communicate regardless of their programming language. Objects in JSON can be nested, and multiple values can be stored in arrays. If an attribute has no value, it can be set as null. JSON provides a flexible and versatile way to exchange data between systems.

First Java Code With REST API

1
More About Spring Framework

The Spring framework offers numerous benefits for application development. Developers often encounter repetitive patterns in their code, such as connecting to databases, but with Spring, these patterns can be simplified and accelerated through its collection of reusable code. This comprehensive framework covers various aspects of enterprise programming and is highly compatible and proven. The best part is that Spring is open-source and free to use, allowing developers to increase productivity without the need to purchase licenses. Additionally, Spring has a large and supportive developer community, along with well-written documentation, making it easy to learn and seek assistance. One key concept in Spring is "Inversion of Control" (IoC), where object dependencies are managed by the framework, reducing code complexity.

2
Why Spring Boot?

Spring Boot is a powerful tool that simplifies the configuration process in Spring. Spring Boot automates repetitive tasks by providing default configurations that can be overridden if necessary. Developers only need to set up values for pre-defined configurations in files like "application.properties" or "application.yml". Spring Framework offers a wide range of libraries for Java programming, and Spring Initializr is an online project generator that allows developers to select the desired Spring technologies and generate initial scripts. Gradle is used as the dependency management tool in this course. By using Spring Boot and Spring Web, developers can create traditional-style REST APIs easily.

3
Hello Spring Boot

In this lecture, we will build a simple "Hello World" application using Spring Boot. The application will be a Spring REST API hosted on localhost port 8080. It will have only one API that, when requested, will return the string "Welcome to Spring Boot". For now, we will return plain text and not use JSON as the data format. To access the API, we can use a web browser or Postman. We will learn about the Spring annotations "@RestController" and "@RequestMapping", which play a significant role in defining REST APIs.

4
Try API Using Postman

In this lecture, we will explore Postman, a comprehensive API development tool. Postman offers features for sending requests, examining responses, and more. It allows us to work with different HTTP methods, handle request bodies and headers, and provides advanced functionalities. By using Postman, we can easily test and interact with our APIs. It simplifies the process of API development and testing.

5
HTTP Method for Hello World
6
Practical Tips : Using Eclipse

In this lecture, we will discuss some tips for improving source code readability in Eclipse. It is recommended to keep your code well-formatted with proper indentation and line breaks. Eclipse can automatically format your code by pressing CTRL-SHIFT-F. Additionally, Eclipse provides features for importing libraries and removing unused imports. You can use CTRL-SPACE for autocompleting imports and CTRL-SHIFT-O to organize imports. Unused imports can clutter your code, and Eclipse will highlight them as warnings. Enabling automatic formatting and organizing imports on save can help maintain clean source code. Another option is to use the EditorConfig plugin for consistent formatting rules across different editors.

7
Gradle

In this lecture, we will learn about Gradle, a powerful build and dependency management tool. Gradle automates the build process, including compiling source code, packaging, and running tests. It simplifies the management of external libraries and their dependencies, automatically downloading and linking them to your project. With Gradle, you can easily add libraries like Apache Commons Lang3 by defining dependencies in the build.gradle file. Gradle also supports versioning, allowing you to manage and update library versions easily. To use Gradle, you need to configure the build.gradle file in your Java project. Once configured, Gradle will handle the build and dependency management tasks for you.

8
Tips : Semantic Versioning

The numbering convention used in software versions is called semantic versioning (semver). It consists of three parts: major, minor, and patch numbers. The major number indicates significant changes that are not backward compatible. The minor number represents new features or enhancements that are backward-compatible. The patch number signifies bug fixes or changes that do not affect backward compatibility. By following semver, users can understand the severity of changes in each release. While semantic versioning is not mandatory, it is a widely accepted convention among software users. Each part of the version number increments according to specific rules, and incrementing a higher number resets the lower numbers back to zero.

9
Automatic Reload with Spring Boot Devtools

Spring DevTools is a solution provided by Spring that automatically restarts the server whenever changes are saved in the Java classpath. It eliminates the need for manual server restarts, which can be time-consuming and reduce productivity. By default, Spring DevTools monitors specific folders in the classpath for changes. To include Spring DevTools in your project, you need to add the dependency in the build.gradle file. It significantly improves the development experience by providing faster server restarts and streamlining the development workflow.

Application Deployment

1
Create Executable Jar

In order to distribute your application effectively, it needs to be packaged into an executable JAR file. This JAR file acts as a standalone application that can be run on any machine with Java Virtual Machine compatibility. By generating the executable JAR, you can distribute your application easily without the need for the source code or development environment. The JAR file contains all the necessary components to run the application, making it convenient for deployment.

2
Create Deployable War

Introducing an alternative approach for distributing your Java application - deploying it as a WAR (Web Archive) file. While executable JARs package a web server into a single file, WAR files are specifically designed for deployment on Java servers. Popular servers like Apache Tomcat, Jetty, or JBoss are commonly used for this purpose. To generate a WAR file, you can leverage the Spring Initializr tool and adjust the build configuration accordingly. Once generated, the WAR file can be easily uploaded and deployed on your preferred Java server. Simplify your application deployment process by exploring this convenient option.

3
Deploy as Docker

Discover the power of containerization for your Java application deployment. Containers provide a modern and lightweight approach, with Docker being a popular container technology. By leveraging containers, you can ensure consistent application performance across different environments. With the ability to package the application, runtime environment, and proper initialization instructions, containers offer seamless deployment and execution. Take advantage of this efficient deployment option, allowing your application to run smoothly on any machine. Explore the benefits of containerization and streamline your deployment process today.

4
Spring Boot Configuration

Experience flexibility in running your Java application by customizing the server port. With Spring Boot's built-in configurations, you have the power to define your preferred port. Simply modify the application.properties or application.yml file, located under src/main/resources, and set the desired port value. Whether it's changing from the default port 8080 to port 8001 or any other port of your choice, Spring Boot makes it effortless. Take full control of your application's deployment and access it with ease. Explore the extensive list of configurable keys provided by Spring Boot and tailor your application to your specific needs.

Version Control Using Git

1
Version Control, Git, & Github

Version control is like having a backup for your source code, just like Andy, Alice, and Bob did with their Monopoly game. It allows you to restore previous versions of your code, ensuring that you can always go back to a stable state. Without version control, maintaining multiple backups becomes challenging and time-consuming. However, with tools like Git and platforms like GitHub, you can easily manage your code's history and collaborate with others. GitHub, GitLab, and Bitbucket are popular cloud-based Git repositories that offer security and seamless collaboration for developers and companies worldwide. Join the community and discover the power of version control in safeguarding your code and streamlining your development process.

2
Git Basic Commands
3
Creating Github Repository

Create a Git repository effortlessly. Sign in to your GitHub account, click "New repository," and give it a name, such as "practical-java." Choose between public or private repositories to suit your needs. Be cautious not to include sensitive information in public repositories. Say goodbye to complicated setup processes and streamline your workflow with Practical Java's gitignore functionality. Keep your repository clean by ignoring unnecessary files, such as compiled or temporary files.

4
Git Basic Usage

Simplify Code Management with Git! Easily track changes, collaborate seamlessly, and manage versions of your project. Clone remote repositories, make local modifications, and create save points or commits. Push your changes to the remote repository to keep everyone synchronized. Git's intuitive interface and integration with popular IDEs make code comparison and restoration a breeze. Start streamlining your workflow and enhancing collaboration today with Git!

Log

1
What is Log?

Logging is a vital process in programming that helps record and track important events, such as errors and debugging information. It enables developers to analyze program behavior and identify issues efficiently. In development environments, programmers have full control over logging, allowing them to easily troubleshoot and gather necessary information. However, in test or production environments, constant monitoring is impractical. Logging helps by documenting events for future reference, facilitating effective troubleshooting and problem replication. With frameworks like Logback in Spring Boot, developers gain better control and flexibility in logging, defining what events to log and where to store the logs.

2
Log & Version Control

Spring REST Server - Producing JSON (Part One)

1
What We Will Build : JSON

Learn the seamless conversion between JSON and Java in this lecture. Convert your POJOs to JSON effortlessly and vice versa. Spring Boot's inclusion of the Jackson library enables automatic conversion with minimal effort. Build a simple Car API with brand, color, and type attributes. Create endpoints for Java to JSON and JSON to Java conversions. Follow best practices by versioning your API for smooth transitions. Enjoy the convenience of Spring's dependency injection using annotations like @Autowired and @Service.

2
Creating JSON Response

Learn how to create a Car class with brand, color, and type attributes effortlessly. Generate getters, setters, and toString method with a simple right-click. Clean up your source code for better readability. Build the CarService interface with predefined lists of attributes. Implement the RandomCarService to generate random combinations. Create a REST API with the CarApi class and utilize the @Autowired annotation for dependency injection. Retrieve a random car by hitting the API endpoint. Experience the seamless conversion of Java objects to JSON automatically. Commit and push your work to GitHub using GitHub Desktop.

3
Practical Tips : Eclipse Package Presentation
4
Creating Request with JSON Body

Discover how to convert JSON to Java effortlessly with our Car API. Modify the API to include a POST endpoint for echoing JSON values. Experience the convenience of logging JSON input at our Java program and returning a descriptive string about the car. No need to handle JSON this time; we'll simply return a simple string. Learn to accept JSON as a request body by annotating the parameter with @RequestBody. Create the echo() method in CarApi.java to handle this new API endpoint. Configure the @PostMapping annotation with the "/echo" path and specify the "consumes" parameter as JSON. Start the server and test the API on Postman by sending a POST request with a JSON request body. Stay tuned for the next lecture to discover what happens in case of errors.

5
Fixing Car API : Public Constructor

Experience seamless JSON to Java conversion with our powerful API. No need to worry about constructors, as Java automatically handles the creation of a public, no-argument constructor for you. In case you have defined other constructors, simply add the no argument constructor manually. To fix any issues, just navigate to Car.java and include the necessary constructor. Give it a try using Postman, and witness the smooth functioning of our API. Feel free to experiment by adding or removing parameters in the JSON body, and see how our API handles it gracefully. Stay tuned to explore more advanced JSON processing tricks in Java.

Spring REST Server- Producing JSON (Part Two)

1
What We Will Build (Part 2)

In this comprehensive course, we explore common JSON use cases in REST API development. Learn how to configure Java with Jackson to handle JSON data effectively. Discover practical techniques for handling numeric, boolean, and Date data types. We also cover working with arrays and collections, returning multiple cars as JSON, and handling nested class relationships. Unlock the full potential of JSON in your Spring Boot projects with this course.

2
Why the JSON response does not show new attributes
3
Fixing Car & Generate Random Car

Discover how to effortlessly convert Java objects to JSON and vice versa in this comprehensive course. Learn the essential concepts of working with Java and JSON, including the importance of providing getters and setters for smooth conversion. Explore practical usage and discover how to handle numeric, boolean, and Date data types effectively. Gain valuable insights into generating random values and working with new attributes in your JSON objects. With Spring's seamless integration, you can easily convert Java objects to JSON and JSON to Java. Simplify your development process and unlock the power of JSON with this course.

4
Working With Collection

Unlock the power of collections in JSON with our comprehensive course. Discover how to seamlessly add additional attributes to your JSON objects, such as a list of strings representing features like GPS, alarm, and more. Learn to handle collections of various data types, including numbers, booleans, and dates, effortlessly. Explore the flexibility of returning collections of objects as JSON, perfect for scenarios where you need to retrieve multiple cars from a database or generate unpredictable counts of rows. With Spring's automatic conversion capabilities, you can simplify your development process and ensure valid JSON output. Join our course now and take your JSON skills to the next level!

5
Java Class as JSON Attribute

Learn how to create specialized classes like Engine and Tire, adding attributes such as fuel type, horsepower, manufacturer, size, and price. With our step-by-step guidance, you'll master the art of generating valid JSON effortlessly. Explore the flexibility of Spring Boot and its Jackson library, as we dive into the world of annotation customization. Take your JSON skills to the next level and unlock a world of possibilities in JSON processing. Join our course now and become a JSON expert!

6
Practical Tips : Validate JSON String
7
More Jackson Annotations

Join us as we explore various use cases that will enhance your JSON handling skills. In this course, you will learn how to format date and time using custom patterns, change field naming styles to suit your preferences, show or hide specific fields based on criteria, and unwrap nested objects for simplified JSON structure. We provide step-by-step guidance on leveraging annotations like @JsonFormat, @JsonNaming, @JsonProperty, @JsonInclude, @JsonIgnore, and @JsonUnwrapped to achieve your desired JSON output. Don't miss this opportunity to level up your JSON expertise. Enroll in our course today!

8
Jackson Annotations

Working With HTTP Request & Spring Data Elasticsearch

1
Elasticsearch Security

Elasticsearch 8 comes with built-in security features, ensuring that your data remains protected through encrypted communication. In our course, we will guide you through the SSL configuration process, including obtaining the Certificate Authority (CA) fingerprint for secure communication. You'll learn how to enable and disable security, set up usernames and passwords for authentication, and even reset your password if needed. We'll also show you how to interact with Elasticsearch using popular tools like Postman, making API integration a breeze. Join our course today and harness the power of Elasticsearch 8 with confidence.

2
Elasticsearch & Spring Data

We cover various aspects of creating and managing APIs, including using HTTP verbs like GET and POST. You'll learn how to handle different types of endpoints, including those with variables in the URL and query parameters. We'll guide you through the process of creating, updating, and deleting data, using both PUT and DELETE requests. Additionally, we'll show you how to work with Elasticsearch, a powerful search engine, and integrate it seamlessly with your application using Spring Data Elasticsearch. With Spring Data, you can simplify data manipulation and leverage the support for various data sources. Join our course today and discover the magic of Spring Data for yourself!

3
Consuming API & Elasticsearch Data Source

In this lecture, we'll guide you through the process of generating thousands random cars and feeding them into Elasticsearch as dummy data. Our step-by-step approach ensures a smooth workflow, similar to working with a relational database. The data source is automatically cleared upon server startup, allowing you to begin with a fresh set of thousands data every time. By leveraging the capabilities of Spring RestTemplate, you'll effortlessly consume Elasticsearch's REST API. Additionally, our course covers important topics like basic authorization, SSL certificate handling, and custom HTTP client configuration. Join us today and gain the skills to create and manage data sources in Elasticsearch like a pro!

4
Basic Elasticsearch Operation Using Postman

Learn basic operations using Postman, including retrieving document counts, creating new entries, and updating records. Harness the power of Elasticsearch's JSON-based data storage and unlock its exceptional search capabilities. Seamlessly integrate Elasticsearch into your Java applications with Spring Data Elasticsearch.

5
Spring Data & Http Variables

Learn various methods to pass request data, including JSON in the request body, path parameters, and query parameters. Our course guides you through the process of handling different data types effectively. Explore the power of Spring Data Elasticsearch and effortlessly manipulate data in Elasticsearch. Gain control over your API by adding business logic and validation. Start your journey to becoming a proficient API developer today!

6
Spring Data Query - Theory

Learn the power of Spring Data for efficient querying. Our comprehensive course covers theory and implementation, providing a solid foundation. Simplify database interactions with consistent rules for relational and non-relational databases. Harness automatic query creation based on method names. Customize queries using @Query annotations for specific syntax. Boost your querying skills with Spring Data's flexibility and simplicity.

7
Spring Data Query - In Action

Discover the simplicity of querying with Spring Data. Easily create queries based on method names and specific parameters. Find cars released after a certain date by utilizing the firstReleaseDate field. Experience the convenience of testing the Spring repository with a GET method in CarApi.java. Effortlessly retrieve a list of cars newer than a specified date by executing the "/cars/date" endpoint. Unleash the power of Spring Data as it generates queries for you, making querying Elasticsearch a breeze. Customize your queries with the @Query annotation for more advanced filtering options. Gain control over your data retrieval process and enhance your Elasticsearch querying skills with Spring Data.

8
Practical Tips : Spring Data - Method Name Cheat Sheet & Elasticsearch Query
9
Pagination & Sorting

Discover the power of pagination and sorting with Spring Data. Effortlessly retrieve specific portions of data and save bandwidth by fetching only what you need. With Spring Data's built-in pagination feature, you can easily specify the page index and the number of elements to be returned. Take control of your data display by implementing sorting based on your preferred criteria. Experience the simplicity and convenience of pagination and sorting with Spring Data, empowering you to optimize your data retrieval process. Start leveraging these powerful features today to enhance the efficiency of your application.

Working With HTTP Headers

1
Working With HTTP Headers

HTTP headers play a crucial role in passing additional information between clients and servers. They consist of key-value pairs within HTTP messages, allowing for enhanced communication. Headers are case-insensitive and separated by a colon, with values following without line breaks. One advantage is the ability to save bandwidth by selectively retrieving and delivering specific data instead of all at once. Standard headers, such as "User-Agent" and "Last-Modified," provide valuable information about browsers, operating systems, and object modification dates. By understanding how to retrieve headers using annotations or Java HTTP requests, you can leverage this valuable data. Whether you're a provider or consumer, standardizing the usage of HTTP headers ensures seamless communication.

Spring REST API Exception Handling

1
Customize HTTP Response

Discover better control over HTTP responses in this lecture. We delve into handling variables and addressing specific scenarios, such as the absence of a desired color in random car searches. Instead of a generic HTTP status 200, we now return status codes like 400 Bad Request to indicate client input issues. To enhance the user experience, we also provide error messages instead of empty collections. This is made possible through the use of Spring's ResponseEntity class, which allows for precise configuration of the HTTP response, including status codes, headers, and body. By leveraging ResponseEntity, we can tailor responses to meet client needs and ensure effective communication between client and server.

2
Practical Tips : Response Entity - Constructor or Builder?
3
Exception Handling at Controller

Exception handling is a critical part of software engineering, and Spring provides a robust mechanism for REST API error management. With dedicated exception handler methods, such as "handleInvalidColorException()," we can effectively handle specific exceptions and provide appropriate responses. By throwing exceptions like java.lang.IllegalArgumentException with informative messages, we communicate the nature of the error to clients. The response is wrapped in the ErrorResponse class, ensuring a well-structured and meaningful error response. Experience this powerful exception handling in action by trying it out on Postman, and witness the seamless execution of our error handler. Stay tuned as we explore handling multiple exception types in the next phase.

4
Handle Multiple Exception Types

Discover the power of handling multiple types of exceptions within a single controller. In addition to the existing numeric color handler, let's tackle the challenge of handling numeric brand. Introducing our custom exception type, IllegalApiParamException, and the corresponding handler, handleNumericBrandException(). With a simple extension of RuntimeException, we've created a robust custom exception class. By checking if the brand is numeric in the findCarsByParam method, we can now throw IllegalApiParamException with a specific message. To handle this unique exception, we've created the handleIllegalApiParamException method, which gracefully returns a ResponseEntity.

5
Global Exception Handling

Experience seamless exception handling within Spring controllers. Each controller handles exceptions within its own class, ensuring efficient error management. However, different controllers require separate exception handler methods to address specific exceptions. Let's explore this concept with the CarPromotionApi, a powerful API for retrieving car promotions. By leveraging the carPromotionService, we guarantee valid promotion types and trigger an IllegalApiParamException when necessary. Test the endpoints on Postman to witness the streamlined exception handling and receive accurate error responses.

REST API Unit Testing

1
About Unit Testing

Ensure the reliability of your code with comprehensive unit testing. Manual testing can be time-consuming, especially when dealing with multiple endpoints. Changes made in one part of the system may unknowingly affect other areas. With unit testing, you can systematically test each endpoint, comparing expected results with actual values. Java provides a robust unit testing framework, and Spring Initializr includes the necessary dependencies for testing with Spring Boot. By implementing unit testing, you can confidently identify and resolve any issues, ensuring the stability and quality of your application.

2
Introducing JUnit Test Case

Create JUnit test cases in the same package as the class to be tested. Each test method is annotated with @Test and has a generated fail() method body. Run the tests to see the results and identify any failures. Focus on implementing the method body for each test case. Annotate the test class with @SpringBootTest and @AutoconfigureMockMvc to configure the Spring environment and enable mocking for API calls. Simulate requests and compare the expected results using MockMvc. Verify that the status is 200 OK and the content matches the expected value. Run the unit tests and celebrate success.

3
Getting Content & Header for Test

Test the "/api/time" method to ensure it generates the correct value within a 30-second range of the current time. Build a mock HTTP GET request and compare the response content to your own logic using the assert() method. Run the test and celebrate the green results. Witness the effectiveness of unit testing as JUnit identifies the failed test case when you modify the logic in the API. Save time by conducting multiple tests and validating changes instantly without opening Postman. Restore the logic in DefaultRestApi and explore further with testing headers using the "api/header-one" endpoint. Perform the request, expect the response body to contain the header values, and watch all tests pass.

4
Testing Car API

Experience the power of unit testing with CarApiTest.Loop the test code to conduct multiple tests within seconds, saving valuable time. Unleash the full potential of unit testing by testing the creation of a new car using a mock POST request with JSON request body simulation. Validate the success of the test by checking the 2xx status code. Witness the efficiency of unit testing in testing API performance with a maximum execution time of 1 second. Explore the capability of adding request parameters to mock requests and test finding cars by path, checking the number of elements returned. Ensure the list is not null and has a size equal to or less than the specified size. Celebrate the green results and deliver better quality software with confidence.

5
Practical Tips : Test Coverage

JUnit provides code coverage to assess test effectiveness. Set targets for code coverage to drive test creation. Execute unit tests for classes to achieve code coverage. High code coverage boosts confidence in software delivery.

Using Elasticsearch & Kibana to Monitor API

1
Disable Elasticsearch Security

Modify Elasticsearch configuration file to set the HTTPS parameter to false. Access Elasticsearch via HTTP on http://localhost:9200. Adjust Spring Boot settings accordingly for seamless operation. Disable security on Kibana by modifying the Kibana configuration file and restarting the server. Access Kibana at http://localhost:5601.

2
API Monitor with Elasticsearch & Kibana

Monitor API performance to make informed improvements. Use tools like Elasticsearch and Kibana for data storage and visualization. Integrate Spring Actuator for automatic data collection. Add Micrometer Elastic dependency to push data to Elasticsearch. Configure data push frequency in application.yml. Start the application and observe data being pushed to Elasticsearch. Generate a large number of requests using Postman to collect metrics. Create graphics and visualizations in Kibana for analysis and monitoring.

3
Visualize API Data

Use Kibana to visualize and analyze API performance data.Identify the relevant index pattern for metrics data. Create a new data view for the metrics index pattern. In Kibana's Discover menu, filter and explore the metrics data. Utilize Kibana's readable format and filtering capabilities for easier data analysis. Build charts and dashboards based on the metrics data in Kibana's Visualize menu. Create visualizations such as line charts to track HTTP request counts and status. Customize the display and colors of the visualizations. Monitor the data in real-time with auto-refresh options.

4
Create a Dashboard

To create a dashboard in Kibana, modify existing visualizations for specific API endpoints and save them with new names. Then, create a new dashboard and add the modified visualizations by dragging and dropping them into the layout. Finally, save the completed dashboard and enjoy the easy data visualization provided by Elasticsearch and Kibana.

5
Practical Tips : Logging & Monitoring Tools

Share Your API with Other Developer!

1
Automatic API Documentation

To create API documentation using OpenAPI specification, add the springdoc-openapi dependency to your project. Create a new configuration class, OpenApiConfig, with minimal configuration and annotate it as @Configuration. Define a method that returns OpenApi and annotate it as @Bean. Expand each API to see detailed information about parameters, requests, and responses. You can also try out the API by clicking the "try it out" button.

2
Customize API Documentation

Springdoc provides annotations to build API documentation. Use `@Tag` at the class level to set the API's documentation and name. Use `@Operation` for methods and specify the API's description. Annotate parameters with `@Parameter`, and use `@ApiResponses` to define possible HTTP status responses. To hide the "Try it out" button, configure the `application.yml` file. With Springdoc, creating and sharing API documentation becomes easy, allowing you to showcase the value of your API to others.

What's Next?

1
What's Next?

Resources & References (Including Bonus)

1
Bonus : Microservices, Message Brokers, & More
2
Download Source Code & Scripts
You can view and review the lecture materials indefinitely, like an on-demand channel.
Definitely! If you have an internet connection, courses on Udemy are available on any device at any time. If you don't have an internet connection, some instructors also let their students download course lectures. That's up to the instructor though, so make sure you get on their good side!
4.6
4.6 out of 5
422 Ratings

Detailed Rating

Stars 5
209
Stars 4
141
Stars 3
50
Stars 2
9
Stars 1
12