Hands-on with Dropwizard REST APIs
Dropwizard is a Relaxation-oriented framework that draws alongside one another a number of Java offers into a cohesive complete. It is an choice to Spring (and Spring’s WebMVC package deal). Dropwizard delivers a extra streamlined knowledge. It adopts even extra configuration by conference than Spring, and removes most of the API surface that is unrelated particularly to providing Relaxation APIs.
Start off a new Dropwizard task
Let’s start by scaffolding a new task via the official Dropwizard Maven archetype. Obtain a comfortable area on your neighborhood process, and from the command line, enter the command in Listing one.
Listing one. Operate the archetype
mvn archetype:deliver -DarchetypeGroupId=io.dropwizard.archetypes -DarchetypeArtifactId=java-simple -DarchetypeVersion=two..
This will operate in interactive manner. I utilized a team ID of com.infoworld and an artifact ID of Demo. I also utilized Demo for the name.
When the archetype finishes deploying itself, you can cd
into your directory (in my case, cd Demo
). Now you set up the dependencies with mvn clear package deal
.
Now the application can be operate with
java -jar target/Demo-one.-SNAPSHOT.jar server
(Try to remember to use the application name you gave it if distinct from Demo.)
If you visit localhost:8080 now, you will be greeted with a default JSON-formatted “not found” error:
"code":404,"information":"HTTP 404 Not Identified"
Map an endpoint
So considerably, the application only returns 404s because no endpoints are mapped. I want to give you a clear being familiar with of how this is completed with Dropwizard. We’ll isolate the course of action by mapping a simple string endpoint.
Action one is to generate a class that acts as the route handler. Try to remember, Dropwizard’s calling in lifestyle is to unite a number of greatest-in-class libraries into an quick-to-use package deal. For supporting RESTful endpoints, Dropwizard makes use of Jersey. Your application currently has Jersey totally set up. The route mappings are completed with the Jersey syntax.
Action two is to sign up the handler class with the application. Let’s acquire these two measures in convert.
Produce a route handler class
By conference, Dropwizard endpoint handlers go in the /src/major/java/com/infoworld/sources folder (or what ever team ID you decide on). We’re heading to include an endpoint handler for returning a record of songwriters. As you can see in Listing two, we’ll return only the greatest. Produce a new SongWriters.java file in the /sources directory.
Listing two. The SongWriters endpoint
package deal com.infoworld.sourcesimport javax.ws.rs.*
import javax.ws.rs.main.MediaType
import java.util.List
import java.util.Optional@Path("/songwriters")
@Produces(MediaType.Application_JSON)
public class SongWriters
public SongWriters()
@GET
public String getBrands()
return "'name':'Roger Waters','name':'Tom Petty'"
Listing two is relatively simple. The class itself is presented a route via the @Path
annotation, and JSON is specified as the media form via the @Produces
annotation. Following, the getBrands()
system, which returns a string, is mapped to the GET HTTP
system via the @GET
annotation. The system just returns a tricky-coded string symbolizing the set of songwriters.
Register the handler
Now to sign up the handler. Open up the /src/major/java/com/infoworld/DemoApplication.java file and modify the operate()
system to appear like Listing three.
Listing three. Registering the SongWriters handler
import com.infoworld.sources.SongWriters
// ...
public void operate(final DemoConfiguration configuration, final Natural environment environment)
SongWriters songWriters = new SongWriters()
environment.jersey().sign up(songWriters)
Again, relatively simple. Listing three imports the class you just established, then makes use of the Natural environment
object to entry Jersey and sign up the handler. Recognize the operate
system also receives a DemoConfiguration
object, which you will see in motion momentarily.
Take a look at the handler
Now if you visit localhost:8080/songwriters, you will get the JSON that you tricky coded. Recognize the process has seamlessly dealt with returning the string as JSON.
Model the area
Now you want to shift from a tricky-coded string to utilizing real area objects. Start off by generating a /src/major/java/com/infoworld/area/SongWriter.java file, and give it the contents of Listing 4.
Listing 4. The SongWriter area model class
package deal com.infoworld.areaimport java.util.ArrayList
import java.util.Listpublic class SongWriter
non-public final String name
non-public List tunes = new ArrayList<>()public SongWriter(final String name, final List tunes)
this.name = name
this.tunes = tunes
public String getName()
return name
public List getSongs()
return this.tunes
Incorporate a repository class
Now we’ll include a repository class to represent the information entry layer. Produce a new folder and file: /src/major/java/com/infoworld/repo/SongWriterRepo.java.
Listing five. The SongWriterRepo class
package deal com.infoworld.repoimport com.infoworld.area.SongWriter
import java.util.List
import java.util.ArrayList
import java.util.Optional
import java.util.stream.Collectorspublic class SongWriterRepo
non-public final List songWriters
public SongWriterRepo()
this.songWriters = new ArrayList()
public SongWriterRepo(List songWriters)
this.songWriters = songWriters
public List findAll()
return songWriters
public Optional getByName(final String name)
return songWriters.stream().filter(sw -> sw.getName().equals(name)).findFirst()
As you can see in Listing five, SongWriterRepo is responsible for returning all the SongWriter objects in a List
via the findAll()
system, whilst the getByName()
system grabs the songwriter specified by the handed in string name.
Use the area layer
Now we’ll use the new layer to generate the JSON returned by the source endpoint. Modify com.infoworld.source.SongWriters to appear like Listing 6.
Listing 6. The modified SongWriters class
package deal com.infoworld.sourcesimport javax.ws.rs.*
import javax.ws.rs.main.MediaType
import java.util.List
import java.util.Optionalimport com.infoworld.repo.SongWriterRepo
import com.infoworld.area.SongWriter@Path("/songwriters")
@Produces(MediaType.Application_JSON)
public class SongWriters
non-public final SongWriterRepo repo
public SongWriters(SongWriterRepo repo)
this.repo = repo
@GET
public List getBrands()
return repo.findAll()
Listing 6 has removed the tricky-coded string in favor of referencing the SongWriterRepo
class, which is set in the constructor. Now acquire a appear at Listing 7, exactly where these lessons are wired alongside one another in the DemoApplication
class.
Listing 7. Wiring the area class in DemoApplication
package deal com.infoworldimport io.dropwizard.Application
import io.dropwizard.setup.Bootstrap
import io.dropwizard.setup.Natural environmentimport com.infoworld.sources.SongWriters
import com.infoworld.repo.SongWriterRepopublic class DemoApplication extends Application
// ...
@Override
public void operate(final DemoConfiguration configuration, final Natural environment environment)
SongWriterRepo swRepo = new SongWriterRepo()
SongWriters songWriters = new SongWriters(swRepo)
environment.jersey().sign up(songWriters)
Return to the DemoApplication
class, and modify it as revealed in Listing 7. Recognize that you now instantiate the SongWriterRepo
object and parameterize the SongWriters
source object before handing it off to Jersey.
Now if you rebuild the task and visit localhost:8080/songwriters, you will uncover an vacant array. Let’s include a tricky-coded songwriter as revealed in Listing eight.
Listing eight. Including a songwriter
public void operate(final DW2Configuration configuration,
final Natural environment environment)List preload = new ArrayList()
preload.include(new SongWriter("Mark Knopfler", new ArrayList()))SongWriterRepo swRepo = new SongWriterRepo(preload)
SongWriters songWriters = new SongWriters(swRepo)
environment.jersey().sign up(songWriters)
Now you will get a end result when you strike the endpoint.
Use the config file
Incorporate a new config file at src/major/sources/Demo-Config.yml and set the contents of Listing 9 in it.
Listing 9. The config YAML
---
songWriters:
- John Lennon
- Jeff Lynne
Now modify the com.infoworld.DemoConfiguration.java file to appear like Listing ten. This file is utilized to model the config file via Jackson.
Listing ten. Config java
package deal com.infoworldimport io.dropwizard.Configuration
import com.fasterxml.jackson.annotation.JsonProperty
import org.hibernate.validator.constraints.*
import javax.validation.constraints.*import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonPropertyimport java.util.List
import java.util.ArrayListpublic class DW2Configuration extends Configuration
non-public ListsongWriters
@JsonCreator
public DW2Configuration(@JsonProperty("songWriters") ListsongWriters)
this.songWriters = songWriters
public ListgetSongWriters()
return this.songWriters
Now use the file in DemoApplication
, as shown in Listing 11.
Listing 11. Applying the config file to preload songwriters in DemoApplication.java
@Override
public void operate(final DemoConfiguration configuration,
final Natural environment environment)List preload = new ArrayList()
configuration.getSongWriters().forEach(sw -> preload.include(new SongWriter(sw, new ArrayList())))
SongWriterRepo swRepo = new SongWriterRepo(preload)
SongWriters songWriters = new SongWriters(swRepo)
environment.jersey().sign up(songWriters)
The major position of the modify in Listing 11 is that the configuration file is hydrated into the DemoConfiguration
class, populating the getSongWriters()
system that is utilized to preload the repository class.
Operate the application with the config file
A compact modify is demanded to operate this application with the config file. Recognize in Listing twelve that the file is referenced right after the contact to server
.
Listing twelve. Functioning the application with the config file
java -jar target/DW2-one.-SNAPSHOT.jar server src/major/sources/DW2-config.yml
Now when you visit the application at localhost:8080/songwriters, you will see the preloaded songwriters.
Dropwizard is a lean choice to Spring-centered RESTful APIs. As you have seen below, it focuses on furnishing a simple but ample stack to deal with these requires.
The sources for the demo application are readily available below.
Copyright © 2021 IDG Communications, Inc.