# 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/v4/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)
<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-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, every MongoDB operator : $eq $ne $gt $gte $lt $lte $in $nin $and $or $nor $not $exists $regex $mod $expr ... + $like $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**

```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 multiTenantInstanceUpdated
    isValidConnectionString
g.sys.cache.getKey setKey removeKey resetCacheDB resetCacheCustomApis resetCacheSystemApis
g.logger.debug log info warn error            g.res.shared.x = …   travels with the request : pre hook → API → post hook
g.shared.x = …                                lives as long as the runner, shared by the requests it serves
await g.sys.db.count({ … }, true)             second argument true : the whole envelope, no throw
import * as utils from 'utils/MyClass'         utility classes
```

**Python**

```python
g.req.body  g.req.query  g.req.params  g.req.headers  g.req.event_data
g.req.auth.authAMUser  .authAMDB  .authGoogle  .authAzure  .authAWS  .authCustom
g.res.output  g.res.status_code  g.res.content_type  g.res.errors  g.res.warnings  g.res.shared
await g.sys.db.get_all('instance', 'database', 'collection', find=…, limit=…, headers=…)   get_all_by_stream get_by_id
    save_single_or_multiple master_save array_operations update_by_id update_many replace_by_id remove_by_id query
    query_by_stream remove_by_query aggregate count distinct distinct_query
await g.sys.db.gen.get_all_gen(…)               the same, schemaless, with the _gen suffix
g.sys.system.encrypt decrypt hash get_token call_external_api execute_query get_secret get_table_meta create_indexes
    drop_indexes get_indexes emit_event emit_event_ws is_valid_data_for_table is_valid_data_for_custom_api
    multi_tenant_instance_updated is_valid_connection_string
g.sys.cache.get_key set_key remove_key reset_cache_db reset_cache_custom_apis reset_cache_system_apis
g.logger.debug log info warn error            g.res.shared.x = …   travels with the request : pre hook → API → post hook
g.shared['x'] = …                             lives as long as the runner, shared by the requests it serves
await g.sys.db.full.count(…)                  full : the whole envelope, no raise
from Tax import add                           utility classes
```

**PHP**

```php
$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', find: …, limit: …, 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
    multiTenantInstanceUpdated isValidConnectionString
$g->sys->cache->getKey setKey removeKey resetCacheDB resetCacheCustomApis resetCacheSystemApis
$g->logger->debug log info warn error          $g->res->shared->x = …   travels with the request : pre hook → API → post hook
$g->shared->x = …                              lives as long as the runner, shared by the requests it serves
$g->sys->db->full->count(…)                    full : the whole envelope, no throw
Tax::add(100)                                  utility classes
```

**C#**

```csharp
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
await g.Sys.Db.GetAll(new GetAll("instance", "database", "collection") { Find = …, Limit = …, Headers = … })   GetAllByStream
    GetById SaveSingleOrMultiple MasterSave ArrayOperations UpdateById UpdateMany ReplaceById RemoveById Query
    QueryByStream RemoveByQuery Aggregate Count Distinct DistinctQuery
await 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
    MultiTenantInstanceUpdated IsValidConnectionString
g.Sys.Cache.GetKey SetKey RemoveKey ResetCacheDB ResetCacheCustomApis ResetCacheSystemApis
g.Logger.Debug Log Info Warn Error            g.Res.Shared["x"] = …   travels with the request : pre hook → API → post hook
g.Shared["x"] = …                             lives as long as the runner, shared by the requests it serves
await g.Sys.Db.Full.Count(…)                  Full : the whole envelope, no throw
Tax.Add(100)                                  utility classes
```

**Go**

```go
g.Req.Body()  g.Req.Query()  g.Req.Params()  g.Req.Headers()  g.Req.EventData()
g.Req.Auth().Map("authAMUser")  "authAMDB"  "authGoogle"  "authAzure"  "authAWS"  "authCustom"
g.Res.Output()  g.Res.SetStatusCode(201)  g.Res.SetContentType("text/html")  g.Res.Errors()  g.Res.Warnings()  g.Res.Shared()
g.Sys.Db.GetAll(am.GetAll{Instance: "instance", Database: "database", Collection: "collection", Find: …, Limit: …})   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
    MultiTenantInstanceUpdated IsValidConnectionString
g.Sys.Cache.GetKey SetKey RemoveKey ResetCacheDB ResetCacheCustomApis ResetCacheSystemApis
g.Logger.Debug Log Info Warn Error            g.Res.Shared()["x"] = …   travels with the request : pre hook → API → post hook
g.Shared.Set("x", …)                          lives as long as the runner, shared by the requests it serves
g.Sys.Db.Full.Count(…)                        Full : the whole envelope ; err is the error of the call alone
tax.Add(100)                                  utility classes : import tax "apimaker/src/utility_classes/utils---Tax"
```

**Rust**

```rust
g.req.body()  g.req.query()  g.req.params()  g.req.headers()  g.req.event_data()   (…_mut() to change them)
g.req.auth()["authAMUser"]  ["authAMDB"]  ["authGoogle"]  ["authAzure"]  ["authAWS"]  ["authCustom"]
g.res.output()  g.res.set_status_code(201)  g.res.set_content_type("text/html")  g.res.errors()  g.res.warnings()  g.res.shared()
g.sys.db.get_all(GetAll::new("instance", "database", "collection").find(…).limit(…))?   get_all_by_stream get_by_id
    save_single_or_multiple master_save array_operations update_by_id update_many replace_by_id remove_by_id query
    query_by_stream remove_by_query aggregate count distinct distinct_query
g.sys.db.get_all_gen(…)?                        the same, schemaless, with the _gen suffix
g.sys.system.encrypt decrypt hash get_token call_external_api execute_query get_secret get_table_meta create_indexes
    drop_indexes get_indexes emit_event emit_event_ws is_valid_data_for_table is_valid_data_for_custom_api
    multi_tenant_instance_updated is_valid_connection_string
g.sys.cache.get_key set_key remove_key reset_cache_db reset_cache_custom_apis reset_cache_system_apis
g.logger.debug log info warn error            g.res.shared_mut()["x"] = …   travels with the request : pre hook → API → post hook
g.shared.set("x", …)                          lives as long as the runner, shared by the requests it serves
g.sys.db.full.count(…)?                       full : the whole envelope, no Err for the errors of the API
use crate::Tax;  Tax::add(100.0)              utility classes
```

**Java**

```java
g.req.getBody()  g.req.getQuery()  g.req.getParams()  g.req.getHeaders()  g.req.getEventData()
g.req.getAuth().getObject("authAMUser")  "authAMDB"  "authGoogle"  "authAzure"  "authAWS"  "authCustom"
g.res.getOutput()  g.res.setStatusCode(201)  g.res.setContentType("text/html")  g.res.getErrors()  g.res.getWarnings()  g.res.getShared()
g.sys.db.getAll(new GetAll("instance", "database", "collection").find(…).limit(…))   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
    multiTenantInstanceUpdated isValidConnectionString
g.sys.cache.getKey setKey removeKey resetCacheDB resetCacheCustomApis resetCacheSystemApis
g.logger.debug log info warn error            g.res.getShared().put("x", …)   travels with the request : pre hook → API → post hook
g.shared.put("x", …)                          lives as long as the runner, shared by the requests it serves
g.sys.db.full.count(…)                        full : the whole envelope, no throw
Tax.add(100)                                  utility classes
```

**Kotlin**

```kotlin
g.req.body  g.req.query  g.req.params  g.req.headers  g.req.eventData
g.req.auth.getObject("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(GetAll("instance", "database", "collection").find(…).limit(…))   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
    multiTenantInstanceUpdated isValidConnectionString
g.sys.cache.getKey setKey removeKey resetCacheDB resetCacheCustomApis resetCacheSystemApis
g.logger.debug log info warn error            g.res.shared["x"] = …   travels with the request : pre hook → API → post hook
g.shared["x"] = …                             lives as long as the runner, shared by the requests it serves
g.sys.db.full.count(…)                        full : the whole envelope, no throw
Tax.add(100.0)                                utility classes
```

## Where things are in the admin panel

| | |
|---|---|
| Instances, databases, tables, schemas, APIs | APIs & Logic → Instance API (DB API) |
| Custom APIs · SSR websites · System APIs · Events · Schedulers · WebSocket events · Initializers · Utility classes · API testing · Test cases · Code finder · i18N · Generated interfaces · Swagger | APIs & Logic |
| Security report · Groups · API users · Auth providers · Secrets · Vulnerabilities · Encrypt strings · Dev accounts | Security |
| ER diagram · Index Maker · Database migration · Auto increments | Database |
| Analytics · Log explorer · Servers · Redis · Git · Log profile · Native process logs · Sandbox settings · Deploy API Maker · Licenses | Operations |
| Any page by its name | ⌘K (Ctrl K) |
