Slide 1

Slide 1 text

Building a RESTful API using Kotlin & SpringBoot Winter 2019

Slide 2

Slide 2 text

Kyle Jablonski I am a Senior Android Engineer at Ticketmaster working on B2B Apps and SDKs. I have been working with Android since late 2010. When I am not writing code, I spend my time with my wife, snowboarding, reading books, attending events and writing articles for my own blog at www.kdotj.com. I am also on the Android Tutorial team Author @ RayWenderlich.com And on the Flutter Tutorial team as an Author @kandroidj 2 SPEAKER

Slide 3

Slide 3 text

Topics of Interest In this talk 1. HTTP basics: status codes, verbs, etc. 2. API Contracts 3. SpringBoot with Kotlin 4. Exception Handling 5. Documentation & Testing with Postman 6. Deployment to Elastic Beanstalk on AWS 7. Wrapping it all up with a CI build that uses the API 3 CONCEPTS

Slide 4

Slide 4 text

Http Status Codes HTTP BASICS Status codes provide important feedback for our API users Client 400s Client Error 400 codes are reserved for client errors Server 500s Server Error 500 codes are reserver for server errors OK 200s Success 200 codes are reserved for success scenarios 100 status codes are used for information scenarios. 300 status codes are used for redirection scenarios. 4

Slide 5

Slide 5 text

5 GET, PUT, POST, OH-My HTTP VERBS GET - Read PUT - Update/Replace POST - Create PATCH - Update/Modify DELETE - Delete Photo by Road trip with Raj on unsplash Photo by Aaron Burden on unsplash Photo by NeONBRAND on unsplash

Slide 6

Slide 6 text

6 Data & Lists of Data API COLLECTIONS & RESOURCES Collections in API development are lists of a type of resource. For example, consider a Shapes API. We can use it to request a list of shapes or a single shape. A Collection is the list and the single shape is a resource. Getting a resource: GET api.shapes.com/shapes/1 - returns a single resource, the square GET api.shapes.com/shapes - returns a collection of shapes

Slide 7

Slide 7 text

7 Agreed Upon Behavior API CONTRACTS An API contract is an agreement about the features and functionality of an application programming interface. In the case of RESTful APIs, it is the endpoints and response objects returned from them. Photo by Cytonn Photography on unsplash

Slide 8

Slide 8 text

How to Build an API using Spring 8 MVP Application Controller Error Handling Configuration

Slide 9

Slide 9 text

Dependencies 9 SET UP So… what’s new in our build.gradle script?

Slide 10

Slide 10 text

Application Create an Application.kt file Add the @SpringBootApplication annotation Call SpringApplication.run() 10 BUILDING A REST API

Slide 11

Slide 11 text

Controllers @RestControler - Another key component that combines the @Controller and @ResponeBody annotations into one. @Controller - a specialization on the Component classes and allows implementation classes to be auto detected @ResponseBody - maps the http response body to a transfer or domain object 11 BUILDING A REST API

Slide 12

Slide 12 text

Mapping methods @GetMapping - another combined annotation that makes it easier to define a GET based request with a path. Alternatively, we could use @RequestMapping but the path and GET operation both need to be passed to the annotation. 12 BUILDING A REST API

Slide 13

Slide 13 text

Request Headers @RequestHeader - Tell spring this parameter should be included as a header in the request By specifying this, we let spring hook into some of its native error handling. 13 BUILDING A REST API

Slide 14

Slide 14 text

Request Params @RequestParam - Tell spring this parameter should be included as an argument to the api Required attribute hooks into the native error handling, as well. 14 BUILDING A REST API

Slide 15

Slide 15 text

Response Api Contracts Matter - notice, each method returns a Response Object. This is part of us honoring the API contract we mentioned earlier. ResponseEntity - by default Spring returns this object which has some basic data for a response, but not enough for a Great API! 15 BUILDING A REST API

Slide 16

Slide 16 text

Upstream Service The core functionality of the API is to generate release notes and return a JSON response containing them. First, we need to talk to the upstream service and get the commit messages. 16 BUILDING A REST API

Slide 17

Slide 17 text

Template Generation We then want to create a templated response using the GithubTemplate class which implements a TemplateGenerator interface with a single generate() method 17 BUILDING A REST API

Slide 18

Slide 18 text

Conditional Logic The API conditionally offers email sending so, we will need to run a different operation in the case of each condition. 18 BUILDING A REST API

Slide 19

Slide 19 text

Error Checking Check to field for validity 19 BUILDING A REST API

Slide 20

Slide 20 text

Create & Send Email Use EmailSender and the githubTemplate to generate the html portion of the email. 20 BUILDING A REST API

Slide 21

Slide 21 text

Other case Lastly, return just the Response when we have a true flag passed in for sendEmail 21 BUILDING A REST API

Slide 22

Slide 22 text

Error Handling Error handling matters with a good API because we signed a contract! Giving your API user a consistent error handling mechanism is both important and necessary for you to hold up your end of the contract. With good error handling, your API users will no what mistake they made Or what limitations your API currently has… Luckily, Spring gives us some of this out of the box with the ResponseEntityExceptionHandler class 22 BUILDING A REST API

Slide 23

Slide 23 text

Configuring Error Handling This can then be easily hooked into Spring’s configuration setup using the @ControllerAdvice annotation which enables the error handling for our controllers. 23 BUILDING A REST API

Slide 24

Slide 24 text

Changing Existing Behavior Because the ResponseEntityExceptionHandler class already has a bunch of error handling built in we can override some of its methods to provide our own behavior! 24 BUILDING A REST API Other errors include: NoHandlerFoundException, HttpMessageNotWriteableException, HttpMessageNotReadableException, And…. Many others Wouldn’t it be nice though to add onto this error handling, in our own way?

Slide 25

Slide 25 text

Adding New Behavior We can also add our own error handling! The controller we wrote earlier included custom request headers. How do we handle those? Create a custom Exception! Add the @ResponseStatus annotation onto a class that extends from Exception 25 BUILDING A REST API

Slide 26

Slide 26 text

Exception Handlers Add an exception handler, annotated of course with the @ExceptionHandler annotation and add the new error handling into our configuration. 26 BUILDING A REST API

Slide 27

Slide 27 text

Wrapping Response Finally, Return a ResponseEntity with the wrapper Response Object 27 BUILDING A REST API

Slide 28

Slide 28 text

Congratulations! You have just built your first RESTful API using Kotlin and the Spring framework. 28 BUILDING A REST API

Slide 29

Slide 29 text

Swagger UI Adding documentation to a spring application is easy! First, we need to add another few dependencies to our build script 29 DOCUMENTATION

Slide 30

Slide 30 text

Swagger UI - Settings AUTOGENERATING DOCUMENTATION WITH SWAGGER @Configuration - tells the Spring application to use this class in the configuration of the application @EnableSwagger2 - tells Spring to enable the Swagger 2 feature @Bean - object that is instantiated, assembled, and otherwise managed by a Spring IoC container. This is Springs dependency injection mechanism. 30 DOCUMENTATION API INFORMATION Wrapped in an ApiInfo object we can add a Title, description & version to the docs

Slide 31

Slide 31 text

Swagger UI - Tons of Annotations METHOD LEVEL ANNOTATIONS We can also add annotations on top of our methods so the API docs read better for each rest endpoint using the @ApiOperation annotation 31 DOCUMENTATION

Slide 32

Slide 32 text

Swagger UI - Tons of Annotations 32 DOCUMENTATION PARAMETER LEVEL ANNOTATIONS And finally on our parameters for the function, we can add the @ApiParam annotation.

Slide 33

Slide 33 text

Using Postman Client 33 CLIENT A great way to test your API is to use the Postman GUI application. It can help you organize requests and save them for future usage and testing.

Slide 34

Slide 34 text

Resources 1. HTTP basics: status codes, verbs, etc. - the internet 2. API Contracts - my opinion 3. SpringBoot with Kotlin - https://bit.ly/2XwrOiM 4. Exception Handling - https://bit.ly/37qtH5a 5. Documentation & Testing with Postman - https://swagger.io/ 6. Deployment to Elastic Beanstalk on AWS 7. Wrapping it all up with a CI build that uses the API 34 CONCEPTS