Use the Spring Web starter dependency to create a REST API in Java with Spring Boot. Many believe you must manually configure a server and handle HTTP requests with complex boilerplate code, but Spring Boot automates this by embedding a server and using annotations to map web requests to Java methods.
Spring Boot Simplifies API Development
Spring Boot allows you to build a production-ready REST API by removing the need for manual XML configuration. It uses a concept called "starter dependencies," which group all the libraries you need for a specific task into one package. For a REST API, the spring-boot-starter-web is the primary tool. It includes an embedded Tomcat server, meaning you do not need to install a separate web server on your machine to run your application.
The framework relies heavily on annotations. These are markers in your code that tell Spring how to treat a class or a method. For example, adding @RestController to a class tells Spring that this class will handle incoming web requests and return the data directly in the response body, usually as JSON. This removes the need to create separate view templates for every single response.
Mapping HTTP Methods to Controller Logic
A REST API communicates using standard HTTP methods. Each method corresponds to a specific action on a resource. You define these actions in your controller class using specific annotations. This structure ensures that your API follows a predictable pattern that other developers can easily understand.
| HTTP Method | Spring Annotation | Typical Action | Expected Result |
|---|---|---|---|
| GET | @GetMapping | Retrieve data | 200 OK with resource |
| POST | @PostMapping | Create data | 201 Created |
| PUT | @PutMapping | Update data | 200 OK or 204 No Content |
| DELETE | @DeleteMapping | Remove data | 204 No Content |
When you use @GetMapping("/users"), any request sent to that specific URL path will trigger the associated Java method. If you need to target a specific item, such as a single user, you use a path variable. By adding @PathVariable to your method argument, Spring extracts the ID from the URL (e.g., /users/5) and passes it into your logic as a variable. This allows you to build dynamic endpoints without writing a new method for every single record in your database.
Managing Data with Entities and Repositories
A common misconception is that the controller should handle the database logic directly. In a professional Spring Boot application, you separate the web layer from the data layer. The controller handles the request, a service layer handles the business logic, and a repository layer handles the database communication. This separation makes your code easier to test and maintain.
To start, you create an Entity class. This is a simple Java class marked with @Entity, which tells Spring Data JPA that this class represents a table in your database. Each field in the class becomes a column in that table. You must define a primary key using the @Id annotation, often combined with @GeneratedValue to let the database handle the numbering automatically.
Next, you create a Repository interface. By extending JpaRepository, you gain access to a suite of built-in methods without writing a single line of SQL. Methods like findAll(), findById(), and save() are provided automatically. If you need a custom query, such as finding a user by their email address, you can simply define a method name like findByEmail(String email), and Spring will generate the SQL query based on the method name.
Handling Request Bodies and Response Statuses
When a client sends data to your API, such as a new user's details during a POST request, the data arrives as a JSON string in the request body. You use the @RequestBody annotation in your controller method to tell Spring to automatically convert that JSON into a Java object. This process is handled by a library called Jackson, which is included by default in the web starter.
Returning a simple object from a method always results in a 200 OK status. However, REST standards require different status codes for different outcomes. To control this, return a ResponseEntity object instead of the raw data. This wrapper allows you to specify the HTTP status code and the headers of the response.
For example, when creating a new resource, you should return HttpStatus.CREATED (201). If a user requests an ID that does not exist, you should return HttpStatus.NOT_FOUND (404). This tells the client exactly what happened without them having to parse the response body to find an error message. A practical rule of thumb is to always return a 4xx code for client errors and a 5xx code for server errors.
Connecting to a Database and Testing
To make your API functional, you must connect it to a database. For development, an in-memory database like H2 is often used because it requires zero installation and wipes clean every time you restart the application. You configure this in the application.properties file by specifying the database URL and driver. For production, you would replace these settings with the credentials for a permanent database like PostgreSQL or MySQL.
Testing your API is the final critical step. Since a REST API does not have a user interface, you cannot test it in a standard browser for POST, PUT, or DELETE requests. You can use tools like Postman or cURL to send specific HTTP requests to your local server (typically running on port 8080). When testing, check that your JSON keys match the field names in your Java classes exactly, as a single typo in a key name will result in a null value in your object.
If you encounter a 404 error while the server is running, check your @RequestMapping paths. Ensure that the base path on the controller and the specific path on the method are combined correctly. For instance, if the controller has @RequestMapping("/api") and the method has @GetMapping("/users"), the full URL is /api/users. Labels and paths can differ slightly depending on the version of Spring Boot you are using, so always refer to the logs in your console to see which endpoints were mapped during startup.
Spring Boot API Security and Validation
Once the basic endpoints work, you need to ensure the data coming in is valid. You can use the spring-boot-starter-validation dependency to add constraints to your entity fields. By adding annotations like @NotNull or @Size(min = 2, max = 30) to your Java fields, you can prevent bad data from entering your database. In the controller, adding @Valid before the @RequestBody argument tells Spring to check these constraints before the method even runs.
Security is another essential layer. Spring Security is the standard tool for protecting your API. You can configure it to require an API key or a JWT (JSON Web Token) for specific endpoints. This prevents unauthorized users from deleting or modifying your data. A common pattern is to leave GET endpoints public for browsing while requiring authentication for POST, PUT, and DELETE actions.
To handle errors gracefully, create a @ControllerAdvice class. This is a global interceptor that catches exceptions thrown by any controller. Instead of the client receiving a generic "Internal Server Error" page, you can return a custom JSON object containing a clear error message and a timestamp. This makes your API much more professional and easier for other developers to integrate with.