Sachin
Sachin

Reputation: 527

Kotlin MongoDB, Get request won't work using the @PathVariable command

Controller:

   @GetMapping("/{id}/")
    suspend fun getProject(@PathVariable pidString: String): ResponseEntity<ProjectDTO> {
        return withContext(Dispatchers.IO) {
            println(pidString)
            val pid = projectService.validateURLProjectId(pidString)
            ResponseEntity.ok(projectService.getProject(pid))
        }
    }

API Request:

http://localhost:8080/65461bff3f2baf0938c6f22e/

The id definitely exists

Error

{
    "status": "BAD_REQUEST",
    "code": 400,
    "timestamp": "2023-11-04T14:07:32.925505",
    "message": "500 INTERNAL_SERVER_ERROR \"pidString\""
}

The problem is, it won't even get to the println(pidString) line, in the console, which makes me think it's something to do with @PathVariable

Any ideas?

Upvotes: 0

Views: 35

Answers (1)

Milinda Shehan
Milinda Shehan

Reputation: 65

It seems like there might be an issue with how you're using the @PathVariable annotation in your Kotlin Spring application.

Check if your Controller is properly mapped

Make sure that your controller is properly mapped to the correct URL pattern. In your case, it seems like you're expecting a request at http://localhost:8080/{id}/, so double-check if your controller class or the method itself is properly annotated with @RestController and if the request mapping is correct.

@RestController
@RequestMapping("/your-endpoint") // Add the endpoint mapping
class YourController {
    // ...
}

Ensure you have the @PathVariable annotation correctly

Double-check that you're using the @PathVariable annotation correctly on the pidString parameter in your getProject method.

@GetMapping("/{id}/")
suspend fun getProject(@PathVariable("id") pidString: String): ResponseEntity<ProjectDTO> {
    // ...
}

Note that the value inside @PathVariable should match the parameter name in your URL.

Check if your projectService is working as expected

Make sure that projectService.validateURLProjectId(pidString) and projectService.getProject(pid) are working correctly. If there's an issue within these methods, it could cause an error.

Check your ProjectDTO class

Ensure that ProjectDTO class is properly defined and that it's not causing any issues.

Upvotes: 0

Related Questions