Building REST API Building REST API with Spring Boot with Spring Boot 1
WHY Spring Boot? You can build REST API WITHOUT Spring Boot What is the need for Spring Boot? HOW to build a great REST API? Identifying Resources (/users, /users/{id}/posts) Identifying Actions (GET, POST, PUT, DELETE, ...) Defining Request and Response structures Using appropriate Response Status (200, 404, 500, ..) Understanding REST API Best Practices Thinking from the perspective of your consumer Validation, Internationalization - i18n, Exception Handling, HATEOAS, Versioning, Documentation, Content Negotiation and a lot more! Building REST API with Spring Boot - Goals Building REST API with Spring Boot - Goals 2
1: Build 3 Simple Hello World REST API Understand the magic of Spring Boot Understand fundamentals of building REST API with Spring Boot @RestController, @RequestMapping, @PathVariable, JSON conversion 2: Build a REST API for a Social Media Application Design and Build a Great REST API Choosing the right URI for resources (/users, /users/{id}, /users/{id}/posts) Choosing the right request method for actions (GET, POST, PUT, DELETE, ..) Designing Request and Response structures Implementing Security, Validation and Exception Handling Build Advanced REST API Features Internationalization, HATEOAS, Versioning, Documentation, Content Negotiation, ... 3: Connect your REST API to a Database Fundamentals of JPA and Hibernate Use H2 and MySQL as databases Building REST API with Spring Boot - Approach Building REST API with Spring Boot - Approach 3
Let's explore some Spring Boot Magic: Enable Debug Logging WARNING: Log change frequently! 1: How are our requests handled? DispatcherServlet - Front Controller Pattern Mapping servlets: dispatcherServlet urls=[/] Auto Configuration (DispatcherServletAutoConfiguration) 2: How does HelloWorldBean object get converted to JSON? @ResponseBody + JacksonHttpMessageConverters Auto Configuration (JacksonHttpMessageConvertersConfiguration) 3: Who is configuring error mapping? Auto Configuration (ErrorMvcAutoConfiguration) 4: How are all jars available(Spring, Spring MVC, Jackson, Tomcat)? Starter Projects - Spring Boot Starter Web (spring-webmvc, spring-web, spring- boot-starter-tomcat, spring-boot-starter-json) What's Happening in the Background? What's Happening in the Background? 4
Build a REST API for a Social Media Application Key Resources: Users Posts Key Details: User: id, name, birthDate Post: id, description Social Media Application REST API Social Media Application REST API 5
GET - Retrieve details of a resource POST - Create a new resource PUT - Update an existing resource PATCH - Update part of a resource DELETE - Delete a resource Request Methods for REST API Request Methods for REST API 6
Users REST API Retrieve all Users GET /users Create a User POST /users Retrieve one User GET /users/{id} -> /users/1 Delete a User DELETE /users/{id} -> /users/1 Posts REST API Retrieve all posts for a User GET /users/{id}/posts Create a post for a User POST /users/{id}/posts Retrieve details of a post GET /users/{id}/posts/{post_id} Social Media Application - Resources & Methods Social Media Application - Resources & Methods 7
Return the correct response status Resource is not found => 404 Server exception => 500 Validation error => 400 Important Response Statuses 200 — Success 201 — Created 204 — No Content 401 — Unauthorized (when authorization fails) 400 — Bad Request (such as validation error) 404 — Resource Not Found 500 — Server Error Response Status for REST API Response Status for REST API 8
Documentation Content Negotiation Internationalization - i18n Versioning HATEOAS Static Filtering Dynamic Filtering Monitoring .... Advanced REST API Features Advanced REST API Features 9
Your REST API consumers need to understand your REST API: Resources Actions Request/Response Structure (Constraints/Validations) Challenges: Accuracy: How do you ensure that your documentation is upto date and correct? Consistency: You might have 100s of REST API in an enterprise. How do you ensure consistency? Options: 1: Manually Maintain Documentation Additional effort to keep it in sync with code 2: Generate from code REST API Documentation REST API Documentation 10
Quick overview: 2011: Swagger Specification and Swagger Tools were introduced 2016: Open API Specification created based on Swagger Spec. Swagger Tools (ex:Swagger UI) continue to exist OpenAPI Specification: Standard, language-agnostic interface Discover and understand REST API Earlier called Swagger Specification Swagger UI: Visualize and interact with your REST API Can be generated from your OpenAPI Specification REST API Documentation - Swagger and Open API REST API Documentation - Swagger and Open API 11
Same Resource - Same URI HOWEVER Different Representations are possible Example: Different Content Type - XML or JSON or .. Example: Different Language - English or Dutch or .. How can a consumer tell the REST API provider what they want? Content Negotiation Example: Accept header (MIME types - application/xml, application/json, ..) Example: Accept-Language header (en, nl, fr, ..) Content Negotiation Content Negotiation 12
Your REST API might have consumers from around the world How do you customize it to users around the world? Internationalization - i18n Typically HTTP Request Header - Accept- Language is used Accept-Language - indicates natural language and locale that the consumer prefers Example: en - English (Good Morning) Example: nl - Dutch (Goedemorgen) Example: fr - French (Bonjour) Example: de - Deutsch (Guten Morgen) Internationalization - i18n Internationalization - i18n 13
You have built an amazing REST API You have 100s of consumers You need to implement a breaking change Example: Split name into firstName and lastName SOLUTION: Versioning REST API Variety of options URL Request Parameter Header Media Type No Clear Winner! Versioning REST API Versioning REST API 14
URI Versioning - Twitter Request Parameter versioning - Amazon (Custom) headers versioning - Microsoft SAME-URL headers=[X-API-VERSION=1] SAME-URL headers=[X-API-VERSION=2] Media type versioning (a.k.a “content negotiation” or “accept header”) - GitHub SAME-URL produces=application/vnd.company.app-v1+json SAME-URL produces=application/vnd.company.app-v2+json Versioning REST API - Options Versioning REST API - Options http://localhost:8080/v1/person http://localhost:8080/v2/person http://localhost:8080/person?version=1 http://localhost:8080/person?version=2 15
Factors to consider URI Pollution Misuse of HTTP Headers Caching Can we execute the request on the browser? API Documentation Summary: No Perfect Solution My Recommendations Think about versioning even before you need it! One Enterprise - One Versioning Approach Versioning REST API - Factors Versioning REST API - Factors 16
Hypermedia as the Engine of Application State (HATEOAS) Websites allow you to: See Data AND Perform Actions (using links) How about enhancing your REST API to tell consumers how to perform subsequent actions? HATEOAS Implementation Options: 1: Custom Format and Implementation Difficult to maintain 2: Use Standard Implementation HAL (JSON Hypertext Application Language): Simple format that gives a consistent and easy way to hyperlink between resources in your API Spring HATEOAS: Generate HAL responses with hyperlinks to resources HATEOAS HATEOAS 17
Serialization: Convert object to stream (example: JSON) Most popular JSON Serialization in Java: Jackson How about customizing the REST API response returned by Jackson framework? 1: Customize field names in response @JSONProperty 2: Return only selected fields Filtering Example: Filter out Passwords Two types: Static Filtering: Same filtering for a bean across different REST API @JsonIgnoreProperties, @JsonIgnore Dynamic Filtering: Customize filtering for a bean for specific REST API @JsonFilter with FilterProvider Customizing REST API Responses - Filtering and more.. Customizing REST API Responses - Filtering and more.. 18
Spring Boot Actuator: Provides Spring Boot’s production- ready features Monitor and manage your application in your production Spring Boot Starter Actuator: Starter to add Spring Boot Actuator to your application spring-boot-starter-actuator Provides a number of endpoints: beans - Complete list of Spring beans in your app health - Application health information metrics - Application metrics mappings - Details around Request Mappings and a lot more ....... Get Production-ready with Spring Boot Actuator Get Production-ready with Spring Boot Actuator 19
1: HAL (JSON Hypertext Application Language) Simple format that gives a consistent and easy way to hyperlink between resources in your API 2: HAL Explorer An API explorer for RESTful Hypermedia APIs using HAL Enable your non-technical teams to play with APIs 3: Spring Boot HAL Explorer Auto-configures HAL Explorer for Spring Boot Projects spring-data-rest-hal-explorer Explore REST API using HAL Explorer Explore REST API using HAL Explorer 20
building-rest-api-with-spring-boot-in28minutes-presentation.pdf

building-rest-api-with-spring-boot-in28minutes-presentation.pdf

  • 1.
    Building REST API BuildingREST API with Spring Boot with Spring Boot 1
  • 3.
    WHY Spring Boot? Youcan build REST API WITHOUT Spring Boot What is the need for Spring Boot? HOW to build a great REST API? Identifying Resources (/users, /users/{id}/posts) Identifying Actions (GET, POST, PUT, DELETE, ...) Defining Request and Response structures Using appropriate Response Status (200, 404, 500, ..) Understanding REST API Best Practices Thinking from the perspective of your consumer Validation, Internationalization - i18n, Exception Handling, HATEOAS, Versioning, Documentation, Content Negotiation and a lot more! Building REST API with Spring Boot - Goals Building REST API with Spring Boot - Goals 2
  • 4.
    1: Build 3Simple Hello World REST API Understand the magic of Spring Boot Understand fundamentals of building REST API with Spring Boot @RestController, @RequestMapping, @PathVariable, JSON conversion 2: Build a REST API for a Social Media Application Design and Build a Great REST API Choosing the right URI for resources (/users, /users/{id}, /users/{id}/posts) Choosing the right request method for actions (GET, POST, PUT, DELETE, ..) Designing Request and Response structures Implementing Security, Validation and Exception Handling Build Advanced REST API Features Internationalization, HATEOAS, Versioning, Documentation, Content Negotiation, ... 3: Connect your REST API to a Database Fundamentals of JPA and Hibernate Use H2 and MySQL as databases Building REST API with Spring Boot - Approach Building REST API with Spring Boot - Approach 3
  • 5.
    Let's explore someSpring Boot Magic: Enable Debug Logging WARNING: Log change frequently! 1: How are our requests handled? DispatcherServlet - Front Controller Pattern Mapping servlets: dispatcherServlet urls=[/] Auto Configuration (DispatcherServletAutoConfiguration) 2: How does HelloWorldBean object get converted to JSON? @ResponseBody + JacksonHttpMessageConverters Auto Configuration (JacksonHttpMessageConvertersConfiguration) 3: Who is configuring error mapping? Auto Configuration (ErrorMvcAutoConfiguration) 4: How are all jars available(Spring, Spring MVC, Jackson, Tomcat)? Starter Projects - Spring Boot Starter Web (spring-webmvc, spring-web, spring- boot-starter-tomcat, spring-boot-starter-json) What's Happening in the Background? What's Happening in the Background? 4
  • 6.
    Build a RESTAPI for a Social Media Application Key Resources: Users Posts Key Details: User: id, name, birthDate Post: id, description Social Media Application REST API Social Media Application REST API 5
  • 7.
    GET - Retrievedetails of a resource POST - Create a new resource PUT - Update an existing resource PATCH - Update part of a resource DELETE - Delete a resource Request Methods for REST API Request Methods for REST API 6
  • 8.
    Users REST API Retrieveall Users GET /users Create a User POST /users Retrieve one User GET /users/{id} -> /users/1 Delete a User DELETE /users/{id} -> /users/1 Posts REST API Retrieve all posts for a User GET /users/{id}/posts Create a post for a User POST /users/{id}/posts Retrieve details of a post GET /users/{id}/posts/{post_id} Social Media Application - Resources & Methods Social Media Application - Resources & Methods 7
  • 9.
    Return the correctresponse status Resource is not found => 404 Server exception => 500 Validation error => 400 Important Response Statuses 200 — Success 201 — Created 204 — No Content 401 — Unauthorized (when authorization fails) 400 — Bad Request (such as validation error) 404 — Resource Not Found 500 — Server Error Response Status for REST API Response Status for REST API 8
  • 10.
    Documentation Content Negotiation Internationalization -i18n Versioning HATEOAS Static Filtering Dynamic Filtering Monitoring .... Advanced REST API Features Advanced REST API Features 9
  • 11.
    Your REST APIconsumers need to understand your REST API: Resources Actions Request/Response Structure (Constraints/Validations) Challenges: Accuracy: How do you ensure that your documentation is upto date and correct? Consistency: You might have 100s of REST API in an enterprise. How do you ensure consistency? Options: 1: Manually Maintain Documentation Additional effort to keep it in sync with code 2: Generate from code REST API Documentation REST API Documentation 10
  • 12.
    Quick overview: 2011: SwaggerSpecification and Swagger Tools were introduced 2016: Open API Specification created based on Swagger Spec. Swagger Tools (ex:Swagger UI) continue to exist OpenAPI Specification: Standard, language-agnostic interface Discover and understand REST API Earlier called Swagger Specification Swagger UI: Visualize and interact with your REST API Can be generated from your OpenAPI Specification REST API Documentation - Swagger and Open API REST API Documentation - Swagger and Open API 11
  • 13.
    Same Resource -Same URI HOWEVER Different Representations are possible Example: Different Content Type - XML or JSON or .. Example: Different Language - English or Dutch or .. How can a consumer tell the REST API provider what they want? Content Negotiation Example: Accept header (MIME types - application/xml, application/json, ..) Example: Accept-Language header (en, nl, fr, ..) Content Negotiation Content Negotiation 12
  • 14.
    Your REST APImight have consumers from around the world How do you customize it to users around the world? Internationalization - i18n Typically HTTP Request Header - Accept- Language is used Accept-Language - indicates natural language and locale that the consumer prefers Example: en - English (Good Morning) Example: nl - Dutch (Goedemorgen) Example: fr - French (Bonjour) Example: de - Deutsch (Guten Morgen) Internationalization - i18n Internationalization - i18n 13
  • 15.
    You have builtan amazing REST API You have 100s of consumers You need to implement a breaking change Example: Split name into firstName and lastName SOLUTION: Versioning REST API Variety of options URL Request Parameter Header Media Type No Clear Winner! Versioning REST API Versioning REST API 14
  • 16.
    URI Versioning -Twitter Request Parameter versioning - Amazon (Custom) headers versioning - Microsoft SAME-URL headers=[X-API-VERSION=1] SAME-URL headers=[X-API-VERSION=2] Media type versioning (a.k.a “content negotiation” or “accept header”) - GitHub SAME-URL produces=application/vnd.company.app-v1+json SAME-URL produces=application/vnd.company.app-v2+json Versioning REST API - Options Versioning REST API - Options http://localhost:8080/v1/person http://localhost:8080/v2/person http://localhost:8080/person?version=1 http://localhost:8080/person?version=2 15
  • 17.
    Factors to consider URIPollution Misuse of HTTP Headers Caching Can we execute the request on the browser? API Documentation Summary: No Perfect Solution My Recommendations Think about versioning even before you need it! One Enterprise - One Versioning Approach Versioning REST API - Factors Versioning REST API - Factors 16
  • 18.
    Hypermedia as theEngine of Application State (HATEOAS) Websites allow you to: See Data AND Perform Actions (using links) How about enhancing your REST API to tell consumers how to perform subsequent actions? HATEOAS Implementation Options: 1: Custom Format and Implementation Difficult to maintain 2: Use Standard Implementation HAL (JSON Hypertext Application Language): Simple format that gives a consistent and easy way to hyperlink between resources in your API Spring HATEOAS: Generate HAL responses with hyperlinks to resources HATEOAS HATEOAS 17
  • 19.
    Serialization: Convert objectto stream (example: JSON) Most popular JSON Serialization in Java: Jackson How about customizing the REST API response returned by Jackson framework? 1: Customize field names in response @JSONProperty 2: Return only selected fields Filtering Example: Filter out Passwords Two types: Static Filtering: Same filtering for a bean across different REST API @JsonIgnoreProperties, @JsonIgnore Dynamic Filtering: Customize filtering for a bean for specific REST API @JsonFilter with FilterProvider Customizing REST API Responses - Filtering and more.. Customizing REST API Responses - Filtering and more.. 18
  • 20.
    Spring Boot Actuator:Provides Spring Boot’s production- ready features Monitor and manage your application in your production Spring Boot Starter Actuator: Starter to add Spring Boot Actuator to your application spring-boot-starter-actuator Provides a number of endpoints: beans - Complete list of Spring beans in your app health - Application health information metrics - Application metrics mappings - Details around Request Mappings and a lot more ....... Get Production-ready with Spring Boot Actuator Get Production-ready with Spring Boot Actuator 19
  • 21.
    1: HAL (JSONHypertext Application Language) Simple format that gives a consistent and easy way to hyperlink between resources in your API 2: HAL Explorer An API explorer for RESTful Hypermedia APIs using HAL Enable your non-technical teams to play with APIs 3: Spring Boot HAL Explorer Auto-configures HAL Explorer for Spring Boot Projects spring-data-rest-hal-explorer Explore REST API using HAL Explorer Explore REST API using HAL Explorer 20