Spring - REST API design and implementation

Reading material

  1. https://stackoverflow.blog/2020/03/02/best-practices-for-rest-api-design/
  2. https://www.linkedin.com/pulse/restful-apis-spring-boot-best-practices-nidhal-naffati
  3. https://www.javaguides.net/2018/06/restful-api-design-best-practices.html

REST API design best practices

Key takeaways

  1. Accept and respond with JSON
  2. Use nouns instead of verbs in endpoint paths
  3. Name collections with plural nouns
  4. Nesting resources for hierarchical objects
  5. Handle errors gracefully and return standard error codes
  6. Allow filtering, sorting, and pagination
  7. Maintain Good Security Practices
  8. Cache data to improve performance
  9. Versioning our APIs

REST API implementation best practices

Key takeaways

  1. Use Descriptive and Consistent URLs
  2. Version Your API
  3. Properly Use HTTP Methods
  4. Implement Proper Error Handling
  5. Implement Pagination and Filtering
  6. Use DTOs (Data Transfer Objects)
  7. Implement Validation
  8. Secure Your API
  9. Rate Limiting
  10. Logging and Monitoring
  11. Documentation
  12. Test Thoroughly
  13. Keep your @Controllers clean and focused
    1. https://en.wikipedia.org/wiki/GRASP_(object-oriented_design)#Controller
    2. Controllers are supposed to be very thin. You can read about the Controller pattern explained as part of GRASP here. You want Controllers to coordinate and delegate, rather than to execute actual business logic. Here are the key practices:
    3. Controllers should be stateless! Controllers are by default singletons and giving them any state can cause massive issues.
    4. Controllers should not execute business logic but rely on delegation.
    5. Controllers should deal with the HTTP layer of the application. This should not be passed down to Services.
    6. Controllers should be oriented around a use-case / business-capability.
    7. To go deeper here, would be to start discussing the best practices for designing REST APIs. These are worth learning about regardless if you want to use Spring Boot.
  14. Build your @Services around business capabilities
    1. Applications with Services called something like AccountService, UserService, PaymentService are much easier to deal with than those with DatabaseService, ValidationService, CalculationService etc.
    2. You could decide to go with a 1-to-1 mapping between Controllers and Services. That would be ideal. That does not mean, that Services can’t use each other!