Skip to Content
Course content

61: Building APIs with Spring Boot and Kotlin

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've noticed a recurring pattern when developers first jump from Java to Kotlin within the Spring ecosystem. They tend to carry over the "Java baggage"—specifically, the habit of using field injection. You'll see codebases littered with @Autowired annotations on lateinit var properties. They think that because Spring is a Java framework, they have to play by those rules to make the dependency injection engine happy.

The "Autowired" Crutch

// This is how many people start. It's technically "correct" in that it works, 
// but it's a missed opportunity for safety.
@RestController
class BookController {
    @Autowired
    lateinit var bookService: BookService 
    
    @GetMapping("/books")
    fun getBooks() = bookService.findAll()
}

The problem here is that you're telling Kotlin, "Trust me, this variable will be initialized later." You've introduced mutability (var) and a potential UninitializedPropertyAccessException if you ever try to instantiate this class in a unit test without starting the entire Spring context. It's clunky, and frankly, it ignores why we chose Kotlin in the first place.

Constructor Injection and the Power of val

In modern Spring, you don't need @Autowired on your fields. Spring is smart enough to see a single constructor and inject the dependencies automatically. By moving your dependencies into the primary constructor, you can use val. This makes your controller immutable and guarantees that the class is never in an invalid state.

// This is the Kotlin way. Clean, immutable, and test-friendly.
@RestController
class BookController(private val bookService: BookService) {
    
    @GetMapping("/books")
    fun getBooks(): List<BookResponse> = bookService.findAll()
}

See the difference? No lateinit, no mutable state. If you want to test this controller, you can just pass a mocked BookService directly into the constructor—no reflection or Spring Runner required. I always tell my juniors: if you're typing @Autowired on a field in 2024, you're probably doing it wrong.

Leveraging Data Classes for API Contracts

One of the most satisfying parts of using Kotlin with Spring is how we handle Data Transfer Objects (DTOs). In Java, you'd have a class with a private constructor, getters, setters, and a 50-line equals() and hashCode() method. In Kotlin, we use data classes. They are perfect for defining the shape of your JSON requests and responses.

// A concise contract for creating a new book
data class CreateBookRequest(
    val title: String,
    val author: String,
    val isbn: String,
    val pageCount: Int? = null // Optional field
)

@PostMapping("/books")
fun createBook(@RequestBody request: CreateBookRequest): ResponseEntity<BookResponse> {
    val book = bookService.save(request)
    return ResponseEntity.ok(book)
}

Because these are data classes, Spring's Jackson integration handles them flawlessly. You get the benefit of strict typing and named arguments without the boilerplate noise. Just be careful not to use your database entities as your API responses; always map your internal models to a DTO to avoid accidentally leaking sensitive database columns to the public internet.

Handling Nullability in Request Params

Spring's @RequestParam and @PathVariable play very nicely with Kotlin's null safety. If you define a parameter as a non-nullable String, Spring will automatically throw an error if that parameter is missing. If you want it to be optional, simply make it nullable.

@GetMapping("/books/search")
fun searchBooks(
    @RequestParam title: String,            // Required: 400 Bad Request if missing
    @RequestParam genre: String? = "Fiction" // Optional: Defaults to "Fiction"
): List<BookResponse> {
    return bookService.search(title, genre)
}

This shifts the validation logic from your method body into the type system itself. You aren't writing if (genre == null) blocks anymore; the language and the framework are handling the contract for you.




📋 Practical Task

Build a "Task Management API" Endpoint

Your goal is to implement a small part of a Task Management system. You need to create a REST controller that allows a user to mark a task as completed.

Requirements:

  • Create a data class TaskUpdateResponse containing a taskId: UUID, status: String, and updatedAt: LocalDateTime.
  • Create a TaskController that uses constructor injection to bring in a (mocked) TaskService.
  • Implement a PATCH endpoint at /tasks/{id}/complete.
  • The endpoint should take a UUID from the path and call a method on the service called markAsComplete(id: UUID).
  • Return the TaskUpdateResponse with a 200 OK status.

Constraint: Do not use @Autowired on any fields. Ensure all dependencies are immutable (val) and defined in the primary constructor.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.