Skip to content

Instantly share code, notes, and snippets.

@key-del-jeeinho
Last active January 9, 2023 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save key-del-jeeinho/6e1e5380ba56d04bfc46033923b11d3b to your computer and use it in GitHub Desktop.
Save key-del-jeeinho/6e1e5380ba56d04bfc46033923b11d3b to your computer and use it in GitHub Desktop.

Sure, here is an example of a simple API for managing accounts using Kotlin and Spring Boot:

import org.springframework.web.bind.annotation.*

@RestController
@RequestMapping("/accounts")
class AccountController {

    val accounts = mutableListOf<Account>()

    @GetMapping
    fun getAccounts() = accounts

    @PostMapping
    fun createAccount(@RequestBody account: Account): Account {
        accounts.add(account)
        return account
    }

    @PutMapping("/{id}")
    fun updateAccount(@PathVariable id: Long, @RequestBody account: Account): Account {
        val index = accounts.indexOfFirst { it.id == id }
        accounts[index] = account
        return account
    }

    @DeleteMapping("/{id}")
    fun deleteAccount(@PathVariable id: Long) {
        accounts.removeIf { it.id == id }
    }

}

data class Account(val id: Long, val name: String)

This API has four endpoints:

GET /accounts: Returns a list of all accounts POST /accounts: Creates a new account PUT /accounts/{id}: Updates an existing account with the given id DELETE /accounts/{id}: Deletes an account with the given id Each account has an id and a name.

This example uses the @RestController annotation to mark the class as a controller that handles HTTP requests, and the @RequestMapping annotation to specify the base path for all endpoints in the controller.

The @GetMapping, @PostMapping, @PutMapping, and @DeleteMapping annotations are used to specify the HTTP verb for each endpoint. The @RequestBody and @PathVariable annotations are used to bind the request body and path variables to method parameters.

I hope this helps! Let me know if you have any questions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment