Curo Blog

Create a REST API in Spring Boot: A Tutorial

June 20, 2026

Creating a REST API in Spring Boot allows developers to build powerful, scalable web services using Java or Kotlin. The framework simplifies the process by handling boilerplate code, allowing you to focus on defining resources, endpoints, and business logic through intuitive annotations. This tutorial walks you through setting up a project, creating controllers, persisting data, and implementing essential features like validation, error handling, and security.

Understanding REST API Fundamentals

REST (Representational State Transfer) is an architectural style for distributed hypermedia systems. It emphasizes a stateless client-server communication model where each request from a client to a server contains all the information needed to understand and process the request.

Key Characteristics of REST APIs

REST APIs are defined by several core characteristics:

  • Stateless: Each request from a client to a server must contain all the information necessary to understand it. The server does not store any client context between requests, which helps with scalability.
  • Resource-based: Everything is treated as a resource, identified by a Uniform Resource Identifier (URI). For example, a specific user might be identified by /api/users/123.
  • HTTP Methods: Standard HTTP methods are used to perform operations on resources:
    • GET: Retrieve a resource.
    • POST: Create a new resource.
    • PUT: Update an existing resource (full replacement).
    • DELETE: Remove a resource.
    • PATCH: Partially update an existing resource.
  • Standard URLs: Resources are accessed via predictable and human-readable URLs.

Data Formats for REST APIs

The primary data format for REST APIs is JSON (JavaScript Object Notation), due to its lightweight nature and ease of parsing.

  • Primary: JSON
  • Alternative: XML, YAML
  • Content Type: The Content-Type header is typically set to application/json for JSON payloads.

An example request to retrieve user data might look like this:

GET /api/users/123 HTTP/1.1
Host: example.com
Accept: application/json

And the corresponding response would contain the resource's state in JSON format:

{
  "id": 123,
  "name": "John Doe",
  "email": "john@example.com",
  "created_at": "2026-01-01T10:00:00Z"
}

Setting Up a Spring Boot Project for a REST API

To create a REST API in Spring Boot, you first need a project foundation. Spring Boot is well-suited for complex enterprise systems, and while Java is a traditional choice, Kotlin is now the preferred language for new projects.

Your project will need the spring-boot-starter-web dependency, which includes everything required for building web applications, including RESTful ones. This starter pulls in Spring MVC, an embedded Tomcat server, and Jackson for JSON serialization. For a production-grade application, you will also add dependencies for data persistence, security, and validation.

Building the API: Controllers and Endpoints

Once the project is set up, the core of the API is built using controllers, which handle incoming HTTP requests and return responses.

Creating a REST Controller

In Spring Boot, a controller is a class responsible for processing requests. By annotating a class with @RestController, you tell Spring that it will handle web requests. This annotation is a convenience that combines @Controller and @ResponseBody, meaning methods in this class will return data directly in the response body (e.g., as JSON) rather than rendering a view.

Defining Endpoints with HTTP Method Annotations

You define endpoints by creating methods within your controller and mapping them to specific HTTP methods and URL paths using annotations.

  • @GetMapping("/path"): Maps HTTP GET requests. Used for retrieving resources.
  • @PostMapping("/path"): Maps HTTP POST requests. Used for creating new resources.
  • @PutMapping("/path"): Maps HTTP PUT requests. Used for updating an existing resource completely.
  • @DeleteMapping("/path"): Maps HTTP DELETE requests. Used for removing a resource.
  • @PatchMapping("/path"): Maps HTTP PATCH requests. Used for partially updating a resource.

To capture parts of the URL, like an ID, you can use path variables. For example, @GetMapping("/users/{id}") maps to a method that accepts an id parameter annotated with @PathVariable.

Handling Request and Response Bodies

Spring Boot excels at handling data conversion. When a client sends a JSON payload in a POST or PUT request, you can automatically convert it into a Java object by annotating a method parameter with @RequestBody.

Conversely, any object returned from a method in a @RestController is automatically serialized into JSON and sent back in the HTTP response body. For more control over the response, such as setting custom headers or status codes, you can return a ResponseEntity object, which wraps your response body.

Data Persistence with Spring Data JPA

Most APIs need to interact with a database. Spring Data JPA simplifies data persistence by providing a repository programming model that significantly reduces boilerplate code for CRUD (Create, Read, Update, Delete) operations.

To use it, you first define an entity class, which is a simple Java object (POJO) that maps to a database table, using the @Entity annotation. Then, you create a repository interface that extends JpaRepository. Spring automatically provides implementations for standard methods like save(), findById(), findAll(), and deleteById().

Your controller can then be injected with an instance of this repository to interact with the database, allowing you to easily create an API that persists and retrieves resource data.

Enhancing the API with Essential Features

To build a robust, production-ready API, you need to consider validation, error handling, and security.

Validation of Request Data

Ensuring the integrity of incoming data is crucial. Spring Boot integrates with Jakarta Bean Validation (JSR 380), allowing you to add validation constraints directly to your request body objects. By adding annotations like @NotNull, @Size, and @Email to the fields of your class and annotating the corresponding controller method parameter with @Valid, Spring will automatically validate the incoming data. If validation fails, it throws an exception that can be handled gracefully.

Centralized Error Handling

A good API provides clear and consistent error messages. Instead of scattering try-catch blocks throughout your controllers, you can create a centralized exception handler using a class annotated with @ControllerAdvice. Within this class, you can define methods annotated with @ExceptionHandler to catch specific exceptions (like a custom ResourceNotFoundException or a validation failure) and return a standardized JSON error response with an appropriate HTTP status code.

Securing REST APIs

Security is non-negotiable. The spring-boot-starter-security dependency provides a solid foundation for securing your API. Out of the box, it enables basic authentication for all endpoints. For modern REST APIs, this is typically configured to support stateless, token-based authentication schemes like OAuth2 or JSON Web Tokens (JWT). By configuring Spring Security, you can define rules to protect specific endpoints, ensuring that only authenticated and authorized clients can access or modify resources.

Testing Your Spring Boot REST API

Testing is a critical part of the development lifecycle. The spring-boot-starter-test dependency provides a rich set of tools for writing unit and integration tests, including JUnit, Mockito, and Spring Test.

For testing the web layer, you can use the @WebMvcTest annotation. This slices your application context to only include components relevant to MVC, such as your controllers, filters, and JSON serializers, without loading the entire application. This allows you to write fast, focused tests that send mock HTTP requests to your endpoints and assert that the correct responses, status codes, and headers are returned.

Tooling and Performance Considerations

While Spring Boot provides a comprehensive framework, it's part of a larger ecosystem. For documenting your API, standards like OpenAPI 3.1 are highly recommended, as they enable excellent tooling for documentation generation, testing, and mocking.

Regarding performance, applications built on the JVM (like Spring Boot) have some startup overhead. However, this can be mitigated using technologies like GraalVM and Spring Native, which can reduce startup times to under a second. Once warmed up, the JVM delivers excellent throughput, making it suitable for high-load enterprise systems.

Advantages and Disadvantages of REST

Choosing REST for your API development comes with several benefits and some considerations.

Pros of REST API

  • Easy to Learn: Simple and intuitive for developers.
  • Widely Adopted: Extensive documentation and community support.
  • Scalable: Stateless nature facilitates horizontal scaling.
  • Cacheable: Leverages HTTP caching mechanisms effectively at the HTTP and CDN layers.
  • Flexible: Supports multiple data formats like JSON, XML, and YAML.
  • Browser Friendly: Can be tested directly in web browsers.

Cons of REST API

  • Over-fetching: Clients may receive more data than needed.
  • Under-fetching: May require multiple requests to gather related data.
  • No Built-in Schema: API documentation can become outdated without a formal schema definition like OpenAPI.
  • Versioning Challenges: Managing API versions can be complex.
  • Multiple Round Trips: Fetching nested resources often requires several calls.

Comparison with Other API Styles

Understanding REST's place among other API architectural styles is crucial for making informed decisions.

FeatureRESTGraphQLgRPCSOAPWebSocketWebhook
FormatJSON/XMLJSONProtobufXMLJSON/BinaryJSON
ProtocolHTTPHTTPHTTP/2HTTP/SMTPWebSocketHTTP
Learning CurveEasyMediumHardHardMediumEasy
PerformanceGoodGoodExcellentPoorExcellentGood
Real-timeNoYes (subscriptions)YesNoYesYes
Browser SupportExcellentExcellentPoorGoodExcellentN/A
CachingEasyComplexComplexLimitedNoNo
VersioningRequiredNot neededRequiredRequiredN/AN/A
SecurityOAuth/JWTOAuth/JWTSSL/TLSWS-SecurityWSSHMAC
Best ForCRUD appsComplex queriesMicroservicesEnterpriseReal-timeEvents

Frequently Asked Questions

What are the core principles of a REST API?

A REST API is characterized by being stateless, resource-based, using standard HTTP methods (GET, POST, PUT, DELETE, PATCH), and having standard URLs for resource identification.

How do you handle data persistence in a Spring Boot REST API?

Data persistence is typically handled using Spring Data JPA. You define @Entity classes that map to database tables and create JpaRepository interfaces that provide CRUD operations. The controller then uses the repository to manage data.

When should I choose REST over GraphQL?

REST is generally preferred for simple CRUD operations, public APIs where HTTP caching is a priority, and file uploads. GraphQL is better when clients need to request complex or nested data in a single call to avoid under-fetching, or when different clients need different data shapes from the same endpoint.

What is the purpose of the `@RestController` annotation?

@RestController is a convenience annotation in Spring Boot that marks a class as a controller where every method returns a domain object instead of a view. It's a combination of @Controller and @ResponseBody, simplifying the creation of RESTful web services.

Are there any disadvantages to using REST APIs?

Yes, REST APIs can suffer from over-fetching (receiving too much data) and under-fetching (requiring multiple requests for related data). They also lack a built-in schema, which can lead to outdated documentation, and managing API versions can be complex.

Conclusion

Building REST APIs in Spring Boot provides a powerful and efficient way to create robust, scalable web services. By leveraging its auto-configuration, annotation-driven programming model, and rich ecosystem, you can quickly move from initial setup to a fully functional API. This tutorial has shown how to create controllers and endpoints, persist data with Spring Data JPA, and implement crucial features like validation, error handling, security, and testing. While REST has trade-offs like potential over-fetching, its simplicity, wide adoption, and strong tooling make it an excellent choice for a vast range of applications, from public-facing web APIs to the backbone of enterprise systems.

Sources & References

Want to actually learn Web Development & APIs?

Curo turns topics like this into a personalized, guided learning board - built around what you already know. Free to start.

Try Curo
More in Web Development & APIs
Curo

Copyright ©2026 Pixelpath Studio Pvt. Ltd. All rights reserved