Skip to content

Latest commit

 

History

History

NorthwindWebAPI

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 

Lighter Example: Northwind Web API

A server side swift example for accessing the Northwind database using a JSON API and providing a view HTML views to browse them.

Note: The example requires Swift 5.7 / Xcode 14b for proper plugin support.

The example is using the MacroExpress framework, which is like Node.js/Express.js for Swift.

It demonstrates two things:

  • Directly mapping SQLite table records to JSON APIs using Codable. (Including automatic endpoint generation based on the static type information.)
  • Using SQLite table records in Mustache for rendering.

This example works as a plain Swift Package Manager tool or as an Xcode tool target.

Northwind API: Documentation

Running the Example

Either open Package.swift or the xcodeproj in Xcode, select the NorthwindWebAPI tool scheme and press run.

Or on the shell:

$ swift run NorthwindWebAPI

The example can then be accessed at http://localhost:1337/.

Overview

The example in a nutshell:

#!/usr/bin/swift sh
import MacroExpress // @Macro-swift
import Northwind    // @Northwind-swift/NorthwindSQLite.swift

// Get a handle to the database
let db  = Northwind.module!
// Setup the app server
let app = express()
  .use(logger("dev"))
  .set("view engine", "html")
  .set("views", __dirname() + "/views")

// Map `/api/products` to a handler which fetches all "products" from the DB.
// Access using: curl http://localhost:1337/api/products | jq .
app.get("/api/products") { _, res in
  res.send(try db.products.fetch())
}

// We can also autogenerate endpoints for each table automagically.
app.get(db, prefix: "/api/")

app // Those hook up the HTML pages/templates.
  .get("/products.html", products)
  .get("/products/:id/", product)
  .get("/") { _, res in res.render("index") }

app.listen(1337) // start server

Screenshots

MacroSample-Product-List

Macro-Sample-Product-Detail

Who

Lighter is brought to you by Helge Heß / ZeeZide. We like feedback, GitHub stars, cool contract work, presumably any form of praise you can think of.