Hands-on with Dropwizard REST APIs

Dropwizard is a Rest-oriented framework that draws collectively many Java packages into a cohesive entire. It is an alternate to Spring (and Spring’s WebMVC package). Dropwizard provides a a lot more streamlined knowledge. It adopts even a lot more configuration by convention than Spring, and eradicates most of the API area that is unrelated precisely to providing Rest APIs.

Get started a new Dropwizard challenge

Let us get started by scaffolding a new challenge by using the formal Dropwizard Maven archetype. Obtain a cozy position on your local system, and from the command line, enter the command in Listing 1.

Listing 1. Run the archetype

mvn archetype:create -DarchetypeGroupId=io.dropwizard.archetypes -DarchetypeArtifactId=java-very simple -DarchetypeVersion=2..

This will run in interactive manner. I applied a group ID of com.infoworld and an artifact ID of Demo. I also applied Demo for the identify.

When the archetype finishes deploying alone, you can cd into your listing (in my case, cd Demo). Now you put in the dependencies with mvn clear package.

Now the application can be run with

java -jar target/Demo-1.-SNAPSHOT.jar server 

(Keep in mind to use the application identify you gave it if different from Demo.)

If you check out localhost:8080 now, you will be greeted with a default JSON-formatted “not found” error:

"code":404,"concept":"HTTP 404 Not Discovered"

Map an endpoint

So considerably, the application only returns 404s simply because no endpoints are mapped. I want to give you a obvious comprehension of how this is completed with Dropwizard. We’ll isolate the procedure by mapping a very simple string endpoint.

Stage 1 is to make a class that functions as the path handler. Keep in mind, Dropwizard’s calling in everyday living is to unite many finest-in-class libraries into an effortless-to-use package. For supporting RESTful endpoints, Dropwizard utilizes Jersey. Your application currently has Jersey entirely established up. The path mappings are completed with the Jersey syntax.

Stage 2 is to register the handler class with the application. Let us acquire these two measures in transform.

Produce a path handler class

By convention, Dropwizard endpoint handlers go in the /src/major/java/com/infoworld/methods folder (or no matter what group ID you select). We’re heading to increase an endpoint handler for returning a record of songwriters. As you can see in Listing 2, we’ll return only the finest. Produce a new SongWriters.java file in the /methods listing.

Listing 2. The SongWriters endpoint

package com.infoworld.methods

import javax.ws.rs.*
import javax.ws.rs.main.MediaType
import java.util.List
import java.util.Optional

@Route("/songwriters")
@Provides(MediaType.Application_JSON)
public class SongWriters
    public SongWriters()
   

    @GET
    public String getBrands()
        return "'name':'Roger Waters','name':'Tom Petty'"
   

Listing 2 is rather straightforward. The class alone is supplied a path by using the @Route annotation, and JSON is specified as the media form by using the @Provides annotation. Subsequent, the getBrands() approach, which returns a string, is mapped to the GET HTTP approach by using the @GET annotation. The approach just returns a challenging-coded string symbolizing the established of songwriters.

Sign-up the handler

Now to register the handler. Open the /src/major/java/com/infoworld/DemoApplication.java file and modify the run() approach to glimpse like Listing 3.

Listing 3. Registering the SongWriters handler

import com.infoworld.methods.SongWriters
// ...
public void run(closing DemoConfiguration configuration, closing Environment setting)
        SongWriters songWriters = new SongWriters()
        setting.jersey().register(songWriters)
   

Again, rather straightforward. Listing 3 imports the class you just established, then utilizes the Environment object to access Jersey and register the handler. Observe the run approach also gets a DemoConfiguration object, which you will see in motion momentarily.

Check the handler

Now if you check out localhost:8080/songwriters, you will get the JSON that you challenging coded. Observe the system has seamlessly dealt with returning the string as JSON.

Design the area

Now you want to transfer from a challenging-coded string to making use of genuine area objects. Get started by developing 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 com.infoworld.area

import java.util.ArrayList
import java.util.List

public class SongWriter
    private closing String identify
    private List tracks = new ArrayList<>()

    public SongWriter(closing String identify, closing List tracks)
        this.identify = identify
        this.tracks = tracks
   

    public String getName()
      return identify
   

    public List getSongs()
      return this.tracks
   

Insert a repository class

Now we’ll increase a repository class to signify the details access layer. Produce a new folder and file: /src/major/java/com/infoworld/repo/SongWriterRepo.java.

Listing 5. The SongWriterRepo class

package com.infoworld.repo

import com.infoworld.area.SongWriter
import java.util.List
import java.util.ArrayList
import java.util.Optional
import java.util.stream.Collectors

public class SongWriterRepo
  private closing List songWriters
  public SongWriterRepo()
    this.songWriters = new ArrayList()     
 

  public SongWriterRepo(List songWriters)
    this.songWriters = songWriters
 

  public List findAll()
    return songWriters
 

  public Optional getByName(closing String identify)
    return songWriters.stream().filter(sw -> sw.getName().equals(identify)).findFirst()
 

As you can see in Listing 5, SongWriterRepo is responsible for returning all the SongWriter objects in a List by using the findAll() approach, while the getByName() approach grabs the songwriter specified by the passed in string identify.

Use the area layer

Now we’ll use the new layer to drive the JSON returned by the resource endpoint. Modify com.infoworld.resource.SongWriters to glimpse like Listing six.

Listing six. The modified SongWriters class

package com.infoworld.methods

import javax.ws.rs.*
import javax.ws.rs.main.MediaType
import java.util.List
import java.util.Optional

import com.infoworld.repo.SongWriterRepo
import com.infoworld.area.SongWriter

@Route("/songwriters")
@Provides(MediaType.Application_JSON)
public class SongWriters
   private closing SongWriterRepo repo
    public SongWriters(SongWriterRepo repo)
      this.repo = repo
   

    @GET
    public List getBrands()
        return repo.findAll()
   

Listing six has eliminated the challenging-coded string in favor of referencing the SongWriterRepo class, which is established in the constructor. Now acquire a glimpse at Listing 7, in which these classes are wired collectively in the DemoApplication class.

Listing 7. Wiring the area class in DemoApplication

package com.infoworld

import io.dropwizard.Application
import io.dropwizard.set up.Bootstrap
import io.dropwizard.set up.Environment

import com.infoworld.methods.SongWriters
import com.infoworld.repo.SongWriterRepo

public class DemoApplication extends Application
// ...
    @Override
    public void run(closing DemoConfiguration configuration, closing Environment setting)
        SongWriterRepo swRepo = new SongWriterRepo()
        SongWriters songWriters = new SongWriters(swRepo)
        setting.jersey().register(songWriters)
   

Return to the DemoApplication class, and modify it as demonstrated in Listing 7. Observe that you now instantiate the SongWriterRepo object and parameterize the SongWriters resource object before handing it off to Jersey.

Now if you rebuild the challenge and check out localhost:8080/songwriters, you will obtain an empty array. Let us increase a challenging-coded songwriter as demonstrated in Listing 8.

Listing 8. Incorporating a songwriter

public void run(closing DW2Configuration configuration,
                    closing Environment setting)

        List preload = new ArrayList()
        preload.increase(new SongWriter("Mark Knopfler", new ArrayList()))

        SongWriterRepo swRepo = new SongWriterRepo(preload)
        SongWriters songWriters = new SongWriters(swRepo)
        setting.jersey().register(songWriters)
   

Now you will get a final result when you strike the endpoint.

Use the config file

Insert a new config file at src/major/methods/Demo-Config.yml and place the contents of Listing nine in it.

Listing nine. The config YAML

---
songWriters:
  - John Lennon
  - Jeff Lynne

Now adjust the com.infoworld.DemoConfiguration.java file to glimpse like Listing 10. This file is applied to model the config file by using Jackson.

Listing 10. Config java

package com.infoworld

import 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.JsonProperty

import java.util.List
import java.util.ArrayList

public class DW2Configuration extends Configuration
  private List songWriters
  @JsonCreator
  public DW2Configuration(@JsonProperty("songWriters") List songWriters)
          this.songWriters = songWriters
 
  public List getSongWriters()
          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 run(closing DemoConfiguration configuration,
                    final Environment setting)

        List preload = new ArrayList()

        configuration.getSongWriters().forEach(sw -> preload.increase(new SongWriter(sw, new ArrayList())))
        SongWriterRepo swRepo = new SongWriterRepo(preload)
        SongWriters songWriters = new SongWriters(swRepo)
        setting.jersey().register(songWriters)
   

The major position of the adjust in Listing 11 is that the configuration file is hydrated into the DemoConfiguration class, populating the getSongWriters() approach that is applied to preload the repository class.

Run the application with the config file

A little adjust is expected to run this application with the config file. Observe in Listing twelve that the file is referenced following the contact to server.

Listing twelve. Running the application with the config file

java -jar target/DW2-1.-SNAPSHOT.jar server src/major/methods/DW2-config.yml

Now when you check out the application at localhost:8080/songwriters, you will see the preloaded songwriters.

Dropwizard is a lean alternate to Spring-based RESTful APIs. As you have viewed right here, it focuses on giving a very simple but sufficient stack to address these calls for.

The sources for the demo application are out there right here.

Copyright © 2021 IDG Communications, Inc.

Rosa G. Rose

Next Post

Visual Studio feedback upgrade snubs older versions

Fri Dec 24 , 2021
Microsoft is upgrading the feed-back technique for its Visual Studio IDE, but the modifications suggest that end users of older versions of the software will no lengthier be in a position to submit feed-back. The Ship Responses alternatives in the Aid menu and Responses Heart are staying upgraded, the organization […]