Mock a REST API with Pipedream
@dylburger
code:
data:privatelast updated:3 years ago
today
Build integrations remarkably fast!
You're viewing a public workflow template.
Sign up to customize, add steps, modify code and more.
Join 800,000+ developers using the Pipedream platform
steps.
trigger
HTTP API
Deploy to generate unique URL
This workflow runs on Pipedream's servers and is triggered by HTTP / Webhook requests.
steps.
rest_api
auth
to use OAuth tokens and API keys in code via theauths object
code
Write any Node.jscodeand use anynpm package. You can alsoexport datafor use in later steps via return or this.key = 'value', pass input data to your code viaparams, and maintain state across executions with$checkpoint.
async (event, steps) => {
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
}
224
// Please read the README (click the link on the left)
// before running this workflow 

const { basename, dirname } = require("path")
const _ = require("lodash")

// We store data POSTed to the REST API in local workflow state.
// See https://docs.pipedream.com/workflows/steps/code/#managing-state
let checkpoint = $checkpoint || {}
// You can see all the data saved in the REST API at the bottom of this code step
this.savedCheckpoint = checkpoint

// Our key (where we store and retrieve data) is defined 
// by the URL path you sent the HTTP request to.
const path = new URL(event.url).pathname
const key = path === "/" ? path : path.replace(/\/+$/, "")

// Store, retrieve or delete data based on the HTTP method.
switch (event.method) {
  case 'POST':
    post(key)
    break
  case 'PUT':
    update(key)
    break
  case 'PATCH':
    update(key)
    break
  case 'GET':
    get(key)
    break
  case 'DELETE':
    del(key)
    break
  default:
    console.log(`HTTP method ${event.method} doesn't have an action defined.
      Try adding it in the switch statement above!`)
    break
}

function post(key) {
  if (key === '/') {
    respondWithErr("Cannot issue a POST request against the root URI /. Try POSTing to /foo or /test (for example)")
  }

  try {
    // New records in /key get created at /key/1, key/2 ... key/N
    const id = getNextId(checkpoint, key)

    const newResource = _.set({}, getKeyArrayFromPath(key), {
      [id]: JSON.stringify(event.body),
      counter: id + 1,
    })

    $checkpoint = _.merge(checkpoint, newResource)

    // Respond with the ID of the resource and the full path (key/id)
    $respond({
      body: JSON.stringify({
        id,
        key: `${key}/${id}`
      })
    })
  } catch (err) {
    errHandler(err)
  }
}

function update(key) {
  if (key === '/') {
    respondWithErr("Cannot issue a PUT request against the root URI /. Try PUT /foo or /test (for example)")
  }

  // Save the POSTed data
  _.set(checkpoint, getKeyArrayFromPath(key), JSON.stringify(event.body))

  $checkpoint = checkpoint

  // Respond with the ID of the resource and the full path (key/id)
  $respond({
    body: { message: `Updated ${key}`}
  })
}

function get(key) {
  // GET / should return all keys
  if (key === '/') {
    const body = listKeys(checkpoint)
    $respond({
      status: 200,
      body,
    })
    $end("GET /")
  }

  // GET /collection should return items under that key, with their IDs
  // For now we use a quick and dirty check: does the resource end with a digit?
  // If not, it's a collection
  if (!(key.match(/\d+$/))) {
    const keys = listKeys(checkpoint, key)
    if (!keys || !keys.length) {
      console.log("No keys under collection")
      $respond({
        status: 404,
      })
      $end(`No keys at collection ${key}`)
    }
    
    let collection = []
    for (const key of keys) {
      // Keys are the same format as UNIX directories, so we
      // can just retrieve the "filename" to get the ID
      const keyId = basename(key)
      // Skip counter key
      if (keyId === 'counter') {
        continue
      }
      const data = JSON.parse(_.get(checkpoint, getKeyArrayFromPath(key)))
      // IDs should be returned as IDs
      const id = { id: parseInt(keyId) }
      collection.push({
        ...id,
        ...data,
      })
    }

    $respond({
      status: 200,
      body: collection,
    })
    $end(`GET ${key}`)
  }

  try {
    // Get array of path keys
    const data = _.get(checkpoint, getKeyArrayFromPath(key))
    if (!data) {
      $respond({
        status: 404,
      })
      $end(`No data at key ${key}`)
    }
    $respond({
      body: data,
    })
  } catch (err) {
    errHandler(err)
  }
}

function del(key) {
  if (key === '/') {
    // Reset local workflow state
    $checkpoint = {}

    const message = "Deleted all resources, API reset"
    $respond({
      body: { message }
    })
    $end(message)
  }

  // Convert the key to a nested object property, deleting
  // it from $checkpoint
  const keyArray = getKeyArrayFromPath(key)
  removeProperty(checkpoint, keyArray)
  $respond({
    body: { message: `DELETE request received, deleting key ${key}` },
  })
}

function removeProperty(obj, props) {
  delete props.slice(0, -1).reduce((init, curr) => init && init[curr], obj)[[...props].pop()];
}

function getNextId(ch, key) {
  return _.get(ch, getKeyArrayFromPath(key).concat('counter'), 1)
}

// Returns an array of all keys / records
function listKeys(ch, collection) {
  if (collection) {
    const keyIds = Object.keys(_.get(ch, getKeyArrayFromPath(collection), {}))
    // Return formatted collection + key paths like /collection/1, /collection/2
    return keyIds.map(k => `${collection}/${k}`)
  }
  // Else, list all keys under all collections
  return listAllNestedKeys(ch, '')
}

// List all nested keys under all objects
function listAllNestedKeys(obj, pathSoFar) {
  return _.compact(_.flattenDeep(Object.keys(obj).map(key => {
    if (_.isObject(obj[key])) {
      return listAllNestedKeys(obj[key], pathSoFar + `/${key}`)
    }
    if (key !== 'counter') {
      return pathSoFar + `/${key}`
    }
  })))
}

function getKeyArrayFromPath(path) {
  return path.split("/").slice(1)
}

function respondWithErr(error) {
  $respond({
    status: 400,
    body: { error },
  })
  $end("Error running workflow")
}

function errHandler(err) {
  if (err.response && err.response.status && err.response.status === 404) {
    $respond({
      status: err.response.status,
    })
  }
  throw err
}