DEV Community

Cover image for From 'A' to 'Web App': Build an API in Java

From 'A' to 'Web App': Build an API in Java

Rob OLeary on June 03, 2020

I'm writing this tutorial to fill a void that I have noticed. Building web applications is a top priority for people learning backend development, ...
Collapse
 
zonaut profile image
David Debuck

Great detailed article.
If I can make one suggestion it would be to not use an array for list endpoints but a wrapper object.
The wrapper object could have a property that has that array of users but you could add other properties to the object without breaking the API contract too much over time or even be optional properties.
Pagination could be one example but also other metadata.

Collapse
 
robole profile image
Rob OLeary

Thanks David. Could you point me to a code example of the wrapper class you mentioned?

Collapse
 
zonaut profile image
David Debuck • Edited

I just write my own according to the needs. An example is as follows.
If properties are null than they are not included (Include.NON_NULL) in the json serialization which makes it re-usable for optional properties also

@Getter
@Setter
@JsonInclude(Include.NON_NULL)
public class ResultListDto<T> {

    @JsonProperty("results")
    private List<T> results;

    @JsonProperty("paging")
    private ResultPagingDto paging;

    public ResultListDto() {
    }

    public ResultListDto(List<T> results) {
        this.results = results;
    }
}

Spring HATEOAS for example uses the following github.com/spring-projects/spring-...

Thread Thread
 
robole profile image
Rob OLeary

I see! I am familiar with the DTO pattern. For HATEOAS, its a good use case for a DTO, appending the navigation links without adding logic to the model keeps your classes focused. If I use Spring, I tend to use one of the Spring Data libraries, in your repositories, you can add pagination and sorting, which adds optional parameters to your endpoints. I haven't encountered other situations where I felt a DTO would help me tbh. I was planning to build a complete API soon to see, so you never know!

Thread Thread
 
zonaut profile image
David Debuck • Edited

It's not really a DTO pattern in how people where used to it.
I keep my models only for internal logic and use dto's when I want to expose something to the public. I don't use model mappers that convert a model to a dto, this is just a waste of time and resources. Even with Spring you can read a query directly into a dto and this way my objects are very lean and I can be very specific in what I need to query and expose.
The reason I have my own wrapper object is while I love HATEOAS they have a serious performance impact. For most properties they need to query the DB. I mostly want a count or a next or previous page. I also include other information other than paging so that's also another reason.
Creating dto's for incoming request is in my opinion always a good idea.
I love Spring but frameworks like Spring Boot sometimes take those extra steps that can cause huge problems down the road easily in big enterprise applications or even small ones for that matter, the first thing I always do is set spring.jpa.open-in-view to false, if you don't know what this does you can take a look at it on vladmihalcea.com/the-open-session-...
At the end of the day we need to do what feels most comfortable to us so it's great to see different views on these kinds of subjects.

Thread Thread
 
robole profile image
Rob OLeary • Edited

I understand the motivation. It can be tricky to optimize performance when you use a framework sometimes, you need to override or exclude certain features, and it may not be something that the framework has considered as a use case. Without taking steps like you suggested, the performance of an application would be good for a lot of users. It's a similar problem space that GraphQL looks to solve, request only what you want, and fetch nothing extra from the backend. I am interested in looking into GraphQL.

The challenge I was tackling in this article, and maybe in a follow-up article, is to give a clear and complete path into learning web apis and using spring to do that, what is out there is not very approachable. I was trying to introduce this subject to students who were beginning, and I couldnt assume that they knew about HTTP and design patterns, it is tough to get to a point where you can feel confident making web apps. There isn't many complete example applications out there, the Spring Pet Clinic is still there, but it is a bit out of date.

Thread Thread
 
zonaut profile image
David Debuck

Yes, you're completely right about this, it's not always straight forward for beginners on where to start with these kinds of things.
GraphQL is indeed the next best thing right now and with good reasons, even Github has switched their latest API to it. Bandwidth is very costly so it's always a good idea to save those bytes :p

There are a couple of good new frameworks lately and Micronaut is one of them. I even feel that it feels somewhat simpler for beginners? Maybe it's just me. Testing also seems somewhat more natural to me.

I'm still sticking to Spring though at the moment, I feel it's somewhat more complete at this point in time for my needs.

Anywho, thanks for the article, I look forward to the next one.

Collapse
 
martinkocula profile image
Martin Kocula • Edited

As a HTTP-noob I wanted to follow the link to the corresponding segment instantly.
But it seems like the URL-fragment (learned something!) is broken and needs to contain #http-basics instead of #html-basics.

Collapse
 
robole profile image
Rob OLeary • Edited

That was a mini-test! 😉 Thanks for letting me know. I've fixed the link 👍

Collapse
 
siy profile image
Sergiy Yevtushenko

Spring is one of those things which should be avoided for several reasons. If to keep ones related to teaching Java - Spring heavily uses and promotes a lot a bad practices.

Collapse
 
robole profile image
Rob OLeary • Edited

I think you should have some experience with a language before picking up a framework, so I don't think it is a good idea to teach a framework to a complete beginner. I disagree about Spring heavily using and promoting bad practices. Frameworks are a collection of design patterns, "best practices", and opinions. A best practice is an opinion that a good sized group of people accept, there is still a difference of opinion between people. Sometimes, you like the way a framework does things and sometimes you don't. Sometimes, you must do something a particular way, and other times you can do it your own way. So, you should choose a framework that complements your preferences, and the type of project you are working on. Spring is too popular to ignore, and doesn't deserve to be condemned IMHO!

Collapse
 
siy profile image
Sergiy Yevtushenko • Edited

You may disagree that Spring heavily uses and promotes bad practices, but this does not change the fact that Spring uses exceptions in business logic and uses string constants as code. Both of them are bad practices and there are no disagreement in the Java community in this regard.

As for "too popular": Popularity != Quality and this is especially true in regard to Spring which is poorly designed and even worse implemented. And, fairly speaking, yet another article about Spring has very little value in the sea of similar articles. Article with alternative solutions would be far more useful and interesting. There are a lot of underappreciated and overlooked frameworks which enable writing much faster and much less resource consuming applications.

Don't get me wrong, Spring has it's own uses, but these uses far from "put spring into every single hole around". From my vast experience with Spring, it's best use is a quick'n'dirty MVP to get first round of investment. Then it should be thrown out and rewritten from scratch with other framework, because in long run Spring is quite expensive technology.

Thread Thread
 
robole profile image
Rob OLeary

The article is aimed at less experienced developers. The issue with most tutorials is there is a lot of assumed knowledge, which may pose a challenge for less experienced devs. Being popular means that a developer has a higher chance of working with it, so that is the relevance for me writing about it. I was teaching Java recently and I had this conversation with other devs, we decided to introduce Spring as a framework to them for this reason. I may post about different frameworks in the future and that may be of more interest to you

Thread Thread
 
siy profile image
Sergiy Yevtushenko

Looked more carefully into article and found it really disappointing. The code which most likely beginners will be following in their applications contains a number of significant issues:

  • Using mutable POJO for storing users is a poor habit
  • Using non-synchronized collection for storing data which can be accessed concurrently will result to unpredictable behavior
  • Modifying collection while iterating over it is a poor habit
  • No input validation for REST methods
Collapse
 
pmgysel profile image
Philipp Gysel

Hey Rob, thanks for this great article. It covers a great deal of backend knowledge for starters, neat post!

Collapse
 
robole profile image
Rob OLeary

Thanks. Glad it was helpful Philipp! ☺