# API Maker Cheat Sheet

> The URLs, headers, query params, schema options and g object of API Maker on one page - keep it next to your editor.

Source: https://docs.apimaker.dev/v1/docs/cheat-sheet.html

## URLs

```text
/api/schema/<user-path>/<instance>/<database>/<table>[/operation]     schema APIs (apply the schema)
/api/gen/<user-path>/<instance>/<database>/<table>[/operation]        generated APIs (schemaless)
/api/custom-api/<user-path>/<path of the custom API>                   custom APIs
/api/system-api/<user-path>/<name>                                     system APIs (always POST)
/api/third-party/<user-path>/<bundle>/<version>/<path>                 third party APIs (deprecated)
<instance>::<tenant>                                                   a tenant of a multi-tenant instance
```

| Operation | Method and path suffix |
|---|---|
| Get all · get all by stream | `GET /` · `GET /stream` |
| Get by id | `GET /get-by-id/:id[/:primaryKey]` |
| Save · master save | `POST /save-single-or-multiple` · `POST /master-save` |
| Update by id · update many · replace by id (MongoDB) | `PUT /update-by-id/:id[/:primaryKey]` · `PUT /update-many` · `PUT /replace-by-id/:id[/:primaryKey]` |
| Array operations (MongoDB) | `PUT /array-operations` |
| Remove by id · remove by query | `DELETE /:id[/:primaryKey]` · `POST /query/delete` |
| Query · query by stream | `POST /query` · `POST /query-stream` |
| Count · aggregate (MongoDB) | `POST /count` · `POST /aggregate` |
| Distinct · distinct with query | `GET /distinct/:field[/:order]` · `POST /distinct/:field[/:order]` |

## Headers

| Header | Values |
|---|---|
| `x-am-authorization` | token of the API user (the application) |
| `x-am-user-authorization` · `x-google-authorization` · `x-azure-authorization` · `x-aws-authorization` · `x-custom-authorization` | token of the person, from an auth provider |
| `x-am-response-case` | `noChange` `camelCase` `capitalCase` `constantCase` `dotCase` `headerCase` `noCase` `paramCase` `pascalCase` `pathCase` `sentenceCase` `snakeCase` |
| `x-am-content-type-response` | `application/json` `text/xml` `text/yaml` `text/plain` `text/html` `application/octet-stream` |
| `x-am-response-object-type` | `no_action` `make_flat` |
| `x-am-meta` | `true` : execution time, plan, groups, sandbox in `meta` |
| `x-am-cache-control` | `no_action` `reset_cache` |
| `x-am-get-encrypted-data` | `no_encryption` `get_only_encryption` `get_data_and_encryption` |
| `x-am-encrypted-payload` | `true` when the body is `{ dataEncFE }` |
| `x-am-internationalization` | name of a language of i18N Management |
| `x-am-tenant-username` | tenant of a multi-tenant instance |
| `x-am-sandbox-timeout` | milliseconds, default 13000 |
| `x-am-run-in-sandbox` | `0` any, `1` one sandbox, `n` first n |
| `x-am-secret` | id of another secret |
| `x-no-compression` | `true` |

## Query params (get all, get by id, streams ; in the body for the query APIs)

```text
?find={status:'ACTIVE',price:{$gte:100}}      JSON5 : $eq $ne $gt $gte $lt $lte $in $nin $and $or $not $like $regex $isNull
?select=name,price  ?select=-password          include, or exclude with -
?sort=-created_at,name                         - for descending
?skip=20&limit=10                              paging
?getTotalCount=true                            totalCount in the reply
?deep=[{s_key:'category'}]                     related rows, from the schema relation or with t_instance t_db t_col t_key find select isMultiple limit skip sort deep
?customer_id=42  ?price>=100  ?name=Bob,Alice   any column as a filter
?find={'owner.customer_id':42}                  find and join : a field of a related table
?upsert=true  ?returnDocument=before            update by id
?throwErrorIfRecordNotFound=true               update by id, replace by id, remove by id : 400 instead of null when the id is unknown
```

## Response

```json
{ "success": true,  "statusCode": 200, "data": [], "totalCount": 5, "warnings": [], "logs": [], "meta": {} }
{ "success": false, "statusCode": 400, "errors": [ { "type": "required", "field": "name", "message": "…", "code": 400 } ] }
```

## Schema

```typescript
name: <ISchemaProperty>{
    __type: EType.string,   // string number boolean date objectId file files, [EType.string] for arrays, a nested object for objects
    isPrimaryKey: true,
    isAutoGenerateByAM: { valueGeneratorType: 'ObjectID' | 'GUID_UUID' | 'ULID' | 'ShortUUID' },
    isAutoIncrementByAM: { start: 1000, step: 1 },   // or true
    isAutoIncrementByDB: true,
    isConcurrencyControlField: true,                  // version field of optimistic concurrency control
    validations: { required, min, max, minLength, maxLength, email, enum: [], validatorFun: (value, all) => true },
    conversions: { trim, trimStart, trimEnd, toLowerCase, toUpperCase, conversionFun: (value, all) => value,
                   encryption, hashing, defaults: { defaultValue, defaultFun, shouldReplaceNullWithDefault, shouldReplaceEmptyStringWithDefault } },
    instance: 'x', database: 'y', collection: 'z', column: '_id',   // relation for deep, find and join, master save
    isVirtualField: true, s_columnVirtualLinker: '_id', t_columnVirtualLinker: 'product_id', // one to many
}
```

## The global object g

```typescript
g.req.body  g.req.query  g.req.params  g.req.headers  g.req.eventData
g.req.auth.authAMUser  .authAMDB  .authGoogle  .authAzure  .authAWS  .authCustom
g.res.output  g.res.statusCode  g.res.contentType  g.res.errors  g.res.warnings  g.res.shared
g.sys.db.getAll({ instance, database, collection, queryParams, headers })   getAllByStream getById saveSingleOrMultiple masterSave
    arrayOperations updateById updateMany replaceById removeById query queryByStream removeByQuery aggregate count distinct distinctQuery
g.sys.db.gen.getAllGen(…)                       the same, schemaless, with the Gen suffix
g.sys.system.encrypt decrypt hash getToken callExternalApi executeQuery getSecret getTableMeta createIndexes dropIndexes getIndexes
    emitEvent emitEventWS isValidDataForTable isValidDataForCustomAPI isValidDataForThirdPartyAPI multiTenantInstanceUpdated
g.sys.cache.getKey setKey removeKey resetCacheDB resetCacheCustomApis resetCacheSystemApis resetCacheThirdPartyApis
g.logger.debug log info warn error            g.shared.x = …   shared between hooks and the API
await g.sys.db.count({ … }, true)             second argument true : the whole envelope, no throw
import * as utils from 'utils/MyClass'         utility classes
```

## Where things are in the admin panel

| | |
|---|---|
| Instances, databases, tables, schemas, APIs | API Info → Instance API (DB API) |
| Custom APIs · Events · WebSocket events · Schedulers · Process initializers · API testing · Test cases | API Info |
| Secrets · Groups · API users · Auth providers · Security report · Vulnerabilities | API Security |
| i18N · Log profile · Log explorer · Sandbox settings · Utility classes · Database migration · Code finder · Auto increments · Generated interfaces · Swagger · Deploy API Maker | Utility |
| Analytics · Server nodes · Redis · ER diagram | Dashboard |
