Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Building a RESTful API using Kotlin & Spring Boot

Building a RESTful API using Kotlin & Spring Boot

In this talk, I walk you through building a RESTful API using Kotlin & Spring. You will learn how to build a web service, setup error handling & render documentation for Swagger, as well as, the importance of API contracts.

Kyle Jablonski

November 20, 2019
Tweet

Other Decks in Technology

Transcript

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. How to Build an API using Spring 8 MVP Application

    Controller Error Handling Configuration
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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
  14. 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
  15. 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
  16. Create & Send Email Use EmailSender and the githubTemplate to

    generate the html portion of the email. 20 BUILDING A REST API
  17. Other case Lastly, return just the Response when we have

    a true flag passed in for sendEmail 21 BUILDING A REST API
  18. 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
  19. 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
  20. 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?
  21. 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
  22. 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
  23. Congratulations! You have just built your first RESTful API using

    Kotlin and the Spring framework. 28 BUILDING A REST API
  24. Swagger UI Adding documentation to a spring application is easy!

    First, we need to add another few dependencies to our build script 29 DOCUMENTATION
  25. 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
  26. 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
  27. Swagger UI - Tons of Annotations 32 DOCUMENTATION PARAMETER LEVEL

    ANNOTATIONS And finally on our parameters for the function, we can add the @ApiParam annotation.
  28. 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.
  29. 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