Reactive REST API Using Spring Boot and RxJava

Axellageraldinc Adryamarthanino
2 min readJun 8, 2019

--

I’m not going to explain what and why reactive programming. I hope you’ve read about it somewhere (you can google it). However, I’m going to tell you how to do reactive programming specifically using Spring Boot + RxJava.

Prerequisites

Before you continue reading, I expect you’ve understood about how to create simple REST API using Spring Boot and RxJava. If you haven’t, you can learn about Spring Boot on Baeldung and you can learn about RxJava on androidhive. They explain about those two materials really well.

Reactive REST API

The reactive REST API to be built is just a simple CRUD about authors and books. Here are the endpoints :

[POST] /api/authors → add an author

[POST] /api/books → add a book

[PUT] /api/books/{bookId} → update a book

[GET] /api/books?limit={limit}&page={page} → get list of books

[GET] /api/book/{bookId} → get a book’s detail

[DELETE] /api/book/{bookId} → delete a book

Dependencies

Open your pom.xml and add these dependencies.

P.S. Keep in mind that you have to add the dependency in line 19–23. If you don’t add it as a dependency, you’ll get HttpMediaNotAcceptableException everytime you hit the reactive API. As you can see I also added mockito as dependency for mocking objects in unit tests. But I’ll cover about the unit testing in other article.

Service

For the service layer, the return value is not just regular data types, but I wrapped them inside an RxJava’s Single. For example the code below which handles the addition of a new book.

As you can see, the return value of addBook method is a String wrapped inside RxJava’s Single.

Web/Controller

In the web layer, it just forwards the request to corresponding service, for example as shown above for handling the addition of a new book.

The End

The whole codes (+ unit tests) can be found here → https://github.com/axellageraldinc/reactive-web-api

🎶🎶🎶 If you’re happy and you know it clap your hands 👏👏👏

🎶🎶🎶 Kalau kau suka hati tepuk tangan👏👏👏

--

--

No responses yet