Introduction to Java Web API Integration

Welcome to the fifth lesson of our course on building an image generation service with Java! In our previous lessons, we've built several key components of our application: the PromptManager for formatting user inputs, the ImageManager for storing and processing images, the ImageGeneratorService for connecting to Google's Gemini API, and, most recently, the ImageGeneratorController, which handles input validation and response formatting.

Now it's time to bring everything together by creating a Java web application that will expose our functionality through HTTP endpoints. This is the final piece of our backend architecture that will allow users to interact with our image generation service through a web interface.

In the previous lesson, we built the ImageGeneratorController, which acts as an intermediary between our service layer and the API endpoints we'll create today. The controller handles the business logic of validating inputs, calling the appropriate service methods, and formatting responses. Now, we'll create the web endpoints that will receive HTTP requests from clients and pass them to our controller.

Our Java web API will have three main endpoints:

  1. An endpoint to serve the main HTML page
  2. An endpoint to handle image generation requests
  3. An endpoint to retrieve all previously generated images

By the end of this lesson, you'll have a complete Java web API that integrates with the controller we built previously, providing a clean interface for clients to generate and retrieve images.

Setting Up the Java Web Application

Let's start by setting up our Java web application. In this lesson, we'll use Spring Boot, a popular Java framework for building web applications. Spring Boot simplifies the process of creating stand-alone, production-grade web services with minimal configuration.

To include Spring Boot in your Gradle project, add the following to your build.gradle file:

This configuration applies the Spring Boot plugin and includes the necessary dependencies for building a web application with Spring Boot.

Create the main application class in src/main/java/com/codesignal/Main.java:

This class uses the @SpringBootApplication annotation to enable Spring Boot's auto-configuration and component scanning. The main method starts the embedded web server and launches the application.

With this setup, your Java application is ready to define web endpoints and serve HTTP requests.

Defining API Endpoints

Now that we have our Spring Boot application set up, let's define the endpoints that will handle client requests.

In Spring Boot, endpoints are defined in controller classes using annotations such as @RestController, @GetMapping, and @PostMapping. These annotations map HTTP requests to Java methods, allowing you to handle different types of requests and URLs.

We'll create a new controller class called WebApiController in the com.codesignal.controllers package. This controller will interact with the ImageGeneratorController we built in the previous lesson.

Index Endpoint

We'll start with the index endpoint, which will serve the main HTML page of our application.

In this code, we use the @Controller annotation to indicate that this class handles web requests. The @GetMapping("/") annotation maps GET requests to the root URL (/) to the index() method. Returning the string "image_generator" tells Spring to render the image_generator.html template from the src/main/resources/templates directory.

Make sure you have the image_generator.html file in the correct location so it can be served as the main page.

Generate Image Endpoint

Next, let's define the endpoint for generating images:

Here, we use the @RestController annotation to indicate that this class will handle REST API requests and return JSON responses. The @RequestMapping("/api") annotation sets a base path for all endpoints in this class.

The @PostMapping("/generate_image") annotation maps POST requests to /api/generate_image to the generateImage() method. The @RequestBody annotation tells Spring to parse the incoming JSON request body into a Map<String, String>. We extract the user_input field from the map and pass it to our ImageGeneratorController's generateImage method, which handles the business logic and returns a response.

Get Images Endpoint

Finally, let's define the endpoint for retrieving all previously generated images:

This method is mapped to GET requests at /api/get_images using the @GetMapping annotation. It simply calls the getImages() method of our controller, which retrieves all stored images and returns them as a JSON response.

With these three endpoints, our Java web API provides a complete interface for clients to interact with our image generation service. Clients can view the main page, generate new images, and retrieve previously generated ones.

Configuring Spring Boot

Now that we have our Spring Boot application and endpoints defined, let's configure the server to run our application.

By default, Spring Boot uses an embedded Tomcat server that listens on port 8080. If you want to change the port or other server settings, you can do so in the src/main/resources/application.properties file:

  • server.port=3000 tells Spring Boot to listen on port 3000 for incoming requests.
  • server.address=0.0.0.0 makes the server accessible on all network interfaces.

Once the application is running, you should see output similar to:

You can now access your application by opening a web browser and navigating to http://localhost:3000/ (or the appropriate IP address if accessing from another device).

Summary and Practice Preview

In this lesson, we've built a complete Java web API using Spring Boot that integrates with our ImageGeneratorController to provide a web interface for our image generation service. Let's review what we've accomplished:

  1. We set up a Spring Boot application with the necessary configuration, including port and host settings.
  2. We created an index endpoint to serve the main HTML page of our application.
  3. We implemented a POST endpoint for generating images, which extracts user input from the request and passes it to our controller.
  4. We set up a GET endpoint for retrieving all previously generated images.
  5. We configured the embedded web server to run on a specific port and listen on all network interfaces, with template caching disabled for development.

Our Java web API now provides a complete interface for clients to interact with our image generation service. The API endpoints receive HTTP requests, extract the necessary data, and pass it to our controller, which handles the business logic of validating inputs, calling the appropriate service methods, and formatting responses.

This completes the server-side portion of our image generation application. We've built a robust, modular architecture with a clear separation of concerns:

  • The PromptManager handles prompt formatting
  • The ImageManager manages image storage and processing
  • The ImageGeneratorService connects to the Gemini API and coordinates the other components
  • The ImageGeneratorController validates inputs and formats responses
  • The Java web API routes client requests to the appropriate controller methods

In the upcoming practice exercises, you'll have the opportunity to test the API endpoints we've created. You'll send requests to generate images with different prompts and retrieve the stored images. You'll also explore how the API handles error cases, such as missing or invalid inputs.

By the end of these exercises, you'll have a solid understanding of how to build a complete web API with Java and Spring Boot, integrating it with a controller-based architecture to provide a clean, consistent interface for clients. This knowledge will be valuable not just for image generation services but for any web application you build in the future.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal