Fast pace REST API library for Vapor
This package is intended to speed up backend development using server side swift framework Vapor
Add this package to your Package.swift as dependency and to your target.
dependencies: [
.package(url: "https://github.com/KazaiMazai/vapor-rest-kit", from: "2.0.0")
],
targets: [
.target(name: "App", dependencies: [
.product(name: "VaporRestKit", package: "vapor-rest-kit")
])
]
Import in your code
import VaporRestKit
ResourceUpdateModel, ResourcePatchModel, ResourceOutputModel
protocols:
protocol ResourceUpdateModel: Content, Validatable {
associatedtype Model: Fields
func update(_: Model) -> Model
}
protocol ResourcePatchModel: Content, Validatable {
associatedtype Model: Fields
func patch(_: Model) -> Model
}
protocol ResourceOutputModel: Content {
associatedtype Model: Fields
init(_: Model)
}
Define EagerLoadQueryKeys
, SortQueryKeys
, FilterQueryKeys
if needed
Implement controller with the help of RestKit ResourceController:
struct TodoController {
func create(req: Request) async throws -> Todo.Output {
try ResourceController<Todo.Output>().create(req: req, using: Todo.Input.self)
}
func read(req: Request) async throws -> Todo.Output {
try ResourceController<Todo.Output>().read(req: req)
}
func update(req: Request) async throws -> Todo.Output {
try ResourceController<Todo.Output>().update(req: req, using: Todo.Input.self)
}
func patch(req: Request) async throws -> Todo.Output {
try ResourceController<Todo.Output>().patch(req: req, using: Todo.PatchInput.self)
}
func delete(req: Request) async throws -> Todo.Output {
try ResourceController<Todo.Output>().delete(req: req)
}
func index(req: Request) async throws -> CursorPage<Todo.Output> {
try ResourceController<Todo.Output>().getCursorPage(req: req)
}
}
app.group("todos") {
let controller = TodoController()
$0.on(.POST, use: controller.create)
$0.on(.GET, Todo.idPath, use: controller.read)
$0.on(.PUT, Todo.idPath, use: controller.update)
$0.on(.DELETE, Todo.idPath, use: controller.delete)
$0.on(.PATCH, Todo.idPath, use: controller.patch)
$0.on(.GET, use: controller.index)
}
This will add the following methods to your API endpoint:
HTTP Method | Route | Result |
---|---|---|
POST | /todos | Create new |
GET | /todos/:todoId | Show existing |
PUT | /todos/:todoId | Update existing (Replace) |
PATCH | /todos/:todoId | Patch exsiting (Partial update) |
DELETE | /todos/:todoId | Delete |
GET | /todos | Show paginated list |
Vapor RestKit is licensed under MIT license.