Apikee

Express Example

A complete Express Product API protected with apikee.

Express Example

A complete Product API with swagger-jsdoc, injectSwagger, and requireScope.

Run it

cd examples/express && npm install && npm start

Open http://localhost:3000/docs.

Key setup

import express from 'express'
import swaggerJsdoc from 'swagger-jsdoc'
import swaggerUi from 'swagger-ui-express'
import { apikeeMiddleware, injectSwagger, requireScope } from 'apikee/express'
import { Apikee } from 'apikee'

const app    = express()
const apikee = new Apikee({ secrets: ['local-dev-secret'] })

const spec = swaggerJsdoc({
  definition: { openapi: '3.0.0', info: { title: 'Product API', version: '1.0.0' } },
  apis: ['./server.js'],
})

// One call patches the spec with ApikeeAuth securityScheme
injectSwagger(spec)

app.use('/docs', swaggerUi.serve, swaggerUi.setup(spec))
app.use(apikeeMiddleware({ apikee, excludePaths: new Set(['/health', '/keys']) }))

Routes

app.post('/keys', async (req, res) => {
  const key = await apikee.create(String(req.query.tenant), {
    scopes: String(req.query.scopes ?? 'read,write').split(','),
    expiresIn: '90d',
  })
  res.json({ key })
})

app.get('/products', (req, res) =>
  res.json({ tenant: req.apikee!.tenant, products: [] })
)

app.post('/products', requireScope('write'), (req, res) => {
  res.status(201).json({ ...req.body, tenant: req.apikee!.tenant })
})

app.delete('/products/:id', requireScope('admin'), (req, res) =>
  res.json({ deleted: req.params.id })
)

Try it

curl -X POST "http://localhost:3000/keys?tenant=acme&scopes=read,write"
export KEY="apikee_..."
curl -H "x-api-key: $KEY" http://localhost:3000/products
curl -X POST -H "x-api-key: $KEY" -H "Content-Type: application/json" \
  -d '{"name":"Widget","price":9.99}' http://localhost:3000/products

On this page