Wednesday, May 28, 2025

REST Resource naming convention

 n REST API design, the naming of resources (URLs) should follow consistent and intuitive conventions. When dealing with pluralization, the general best practice is to use plural nouns for resource names, as they represent collections of entities.

Should you use training or trainings in the URL?

  • Use /trainings (plural) when referring to a collection of training resources.

    • ✅ Correct: GET /trainings (retrieve all trainings)

    • ✅ Correct: POST /trainings (create a new training)

    • ✅ Correct: GET /trainings/{id} (retrieve a specific training)

  • Avoid /training (singular) for collections, as it suggests a single resource rather than a collection.

    • ❌ Incorrect (for collections): GET /training

    • ❌ Incorrect (for collections): POST /training

Why Plural (/trainings)?

  1. Consistency with REST conventions – Most REST APIs use plural nouns (e.g., /users/products).

  2. Clarity – GET /trainings clearly indicates you're fetching a list, whereas GET /training could imply a singleton resource.

  3. Predictability – Easier for developers to understand and follow standard patterns.

When to Use Singular (/training)?

Only if you're referring to a singleton resource (a single, global entity). For example:

  • GET /training/config (a single configuration resource for training)

  • PUT /training/settings (global training settings)

But in most cases, /trainings is the correct choice for typical CRUD operations on multiple training records.

Final Recommendation

✅ Use /trainings for standard REST endpoints dealing with multiple training resources.
✅ Use /training/{id} (singular) only when referring to a single training instance.

Example RESTful structure:

Copy
Download
GET    /trainings        → List all trainings  
POST   /trainings        → Create a new training  
GET    /trainings/{id}   → Get a specific training  
PUT    /trainings/{id}   → Update a training  
DELETE /trainings/{id}   → Delete a training  

This follows REST best practices and keeps your API intuitive and consistent.

Sunday, May 25, 2025

Adding Swagger to Spring Boot REST API

 Swagger (now part of the OpenAPI specification) is a powerful tool for documenting and testing your REST APIs. Here's how to integrate it with a Spring Boot application:

1. Add Dependencies

Add these to your pom.xml (Maven) or build.gradle (Gradle):

Maven

xml
Copy
Download
Run
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
    <version>2.5.0</version> <!-- Check for latest version -->
</dependency>

Gradle

groovy
Copy
Download
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.5.0'

2. Basic Configuration

Create a configuration class:

java
Copy
Download
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SwaggerConfig {
    
    @Bean
    public OpenAPI springShopOpenAPI() {
        return new OpenAPI()
                .info(new Info().title("Training Service API")
                        .description("Spring Boot REST API for Training Management")
                        .version("v1.0.0")
                        .license(new License().name("Apache 2.0").url("http://springdoc.org")));
    }
}

3. Annotate Your Controllers

Add Swagger annotations to document your endpoints:

java
Copy
Download
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;

@RestController
@RequestMapping("/api/trainings")
@Tag(name = "Training Controller", description = "Operations related to training sessions")
public class TrainingController {

    @GetMapping
    @Operation(summary = "Get all trainings", description = "Returns list of all available trainings")
    public ResponseEntity<List<Training>> getAllTrainings() {
        // implementation
    }

    @PostMapping
    @Operation(summary = "Create new training", description = "Creates a new training session")
    public ResponseEntity<Training> createTraining(@RequestBody TrainingDto trainingDto) {
        // implementation
    }
}

4. Access Swagger UI

After starting your application, access the UI at:

Copy
Download
http://localhost:8080/swagger-ui.html

Or for the OpenAPI JSON:

Copy
Download
http://localhost:8080/v3/api-docs

5. Advanced Configuration

Custom Path

In application.properties:

properties
Copy
Download
springdoc.swagger-ui.path=/api-docs
springdoc.api-docs.path=/api-docs.json

Security Integration

If using Spring Security:

java
Copy
Download
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()
            // other security config
    }
}

Model Documentation

Annotate your DTOs:

java
Copy
Download
@Schema(description = "Training data transfer object")
public class TrainingDto {
    
    @Schema(description = "Unique identifier of the training", example = "123")
    private Long id;
    
    @Schema(description = "Training title", required = true, example = "Spring Boot Workshop")
    private String title;
    
    // getters and setters
}

6. Grouping APIs

For multiple API groups:

java
Copy
Download
@Bean
public GroupedOpenApi publicApi() {
    return GroupedOpenApi.builder()
            .group("training-public")
            .pathsToMatch("/api/trainings/**")
            .build();
}

@Bean
public GroupedOpenApi adminApi() {
    return GroupedOpenApi.builder()
            .group("training-admin")
            .pathsToMatch("/api/admin/**")
            .build();
}

7. Versioning Support

Document API versions:

java
Copy
Download
@Bean
public OpenAPI customOpenAPI() {
    return new OpenAPI()
        .info(new Info()
            .title("Training API")
            .version("1.0")
            .description("API for training management")
            .termsOfService("http://swagger.io/terms/"))
        .externalDocs(new ExternalDocumentation()
            .description("Training API Wiki Documentation")
            .url("https://example.com/docs"));
}

8. Troubleshooting

Common Issues:

  • 404 on Swagger UI: Ensure you're using the correct path (check springdoc.swagger-ui.path)

  • Missing endpoints: Verify your controllers are in a package scanned by Spring

  • Security blocking access: Configure security to permit Swagger paths

This setup provides:

  • Interactive API documentation

  • Automatic model documentation

  • Try-it-out functionality for endpoints

  • Support for OAuth2 and JWT (with additional configuration)

For the latest updates and features, always check the official documentation.