Skip to content

server.py

Exposed REST API.

protected_route(function)

Protected route function decorator which authenticates requests.

Parameters:

Name Type Description Default
function Callable

Function to decorate, typically routes

required

Returns:

Type Description
Callable

Function's output if JWT authetication is successful, otherwise return error message

Source code in pharus/server.py
 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
def protected_route(function: Callable) -> Callable:
    """
    Protected route function decorator which authenticates requests.

    Args:
        function: Function to decorate, typically routes

    Returns:
        Function's output if JWT authetication is successful, otherwise return error message
    """

    @wraps(function)
    def wrapper(**kwargs):
        try:
            if "database_host" in request.args:
                encoded_jwt = request.headers.get("Authorization").split()[1]
                connect_creds = {
                    "databaseAddress": request.args["database_host"],
                    "username": jwt.decode(
                        encoded_jwt,
                        crypto_serialization.load_der_public_key(
                            b64decode(environ.get("PHARUS_OIDC_PUBLIC_KEY").encode())
                        ),
                        algorithms="RS256",
                        options=dict(verify_aud=False),
                    )[environ.get("PHARUS_OIDC_SUBJECT_KEY")],
                    "password": encoded_jwt,
                }
            else:
                connect_creds = jwt.decode(
                    request.headers.get("Authorization").split()[1],
                    environ["PHARUS_PUBLIC_KEY"],
                    algorithms="RS256",
                )
            connection = dj.Connection(
                host=connect_creds["databaseAddress"],
                user=connect_creds["username"],
                password=connect_creds["password"],
            )
            return function(connection, **kwargs)
        except Exception as e:
            return str(e), 401

    wrapper.__name__ = function.__name__
    return wrapper

api_version()

Handler for /version route.

Returns:

Type Description
str

API version

GET /version

Route to check server health returning the API version.

Example request:
1
2
GET /version HTTP/1.1
Host: fakeservices.datajoint.io
Example response:
1
2
3
4
5
6
7
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json

{
    "version": "0.8.10"
}
Status Codes
  • 200 OK: No error.
Source code in pharus/server.py
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
@app.route(f"{environ.get('PHARUS_PREFIX', '')}/version", methods=["GET"])
def api_version() -> str:
    """
    Handler for ``/version`` route.

    Returns:
        API version

    ## GET /version

    Route to check server health returning the API version.

    ### Example request:

    ```http
    GET /version HTTP/1.1
    Host: fakeservices.datajoint.io
    ```

    ### Example response:

    ```http
    HTTP/1.1 200 OK
    Vary: Accept
    Content-Type: application/json

    {
        "version": "0.8.10"
    }
    ```

    #### Status Codes
    * 200 OK: No error.
    """
    if request.method in {"GET", "HEAD"}:
        return dict(version=version)

login()

Handler for /login route.

Warning

Currently, this implementation exposes user database credentials as plain text in POST body once and stores it within a bearer token as Base64 encoded for subsequent requests. That is how the server is able to submit queries on user's behalf. Due to this, it is required that remote hosts expose the server only under HTTPS to ensure end-to-end encryption. Sending passwords in plain text over HTTPS in POST request body is common and utilized by companies such as GitHub (2021) and Chase Bank (2021). On server side, there is no caching, logging, or storage of received passwords or tokens and thus available only briefly in memory. This means the primary vulnerable point is client side. Users should be responsible with their passwords and bearer tokens treating them as one-in-the-same. Be aware that if your client system happens to be compromised, a bad actor could monitor your outgoing network requests and capture/log your credentials. However, in such a terrible scenario, a bad actor would not only collect credentials for your DataJoint database but also other sites such as github.com, chase.com, etc. Please be responsible and vigilant with credentials and tokens on client side systems. Improvements to the above strategy is currently being tracked in https://github.com/datajoint/pharus/issues/82.

Returns:

Type Description
dict

Function output is an encoded JWT if successful, otherwise return error message

POST /login

Route to generate an authentication token.

Example request:
1
2
3
4
5
6
7
8
9
POST /login HTTP/1.1
Host: fakeservices.datajoint.io
Accept: application/json

{
    "databaseAddress": "tutorial-db.datajoint.io",
    "username": "user1",
    "password": "password1"
}
Example successful response:
1
2
3
4
5
6
7
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json

{
    "jwt": "<token>"
}
Example unexpected response:
1
2
3
4
5
6
HTTP/1.1 500 Internal Server Error
Vary: Accept
Content-Type: text/plain

400 Bad Request: The browser (or proxy) sent a request that this server could not
    understand.
Response Headers
  • Content-Type: text/plain, application/json
Status Codes
  • 200 OK: No error.
  • 500 Internal Server Error: Unexpected error encountered. Returns the error message as a string.
Source code in pharus/server.py
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
@app.route(f"{environ.get('PHARUS_PREFIX', '')}/login", methods=["POST"])
def login() -> dict:
    """
    Handler for ``/login`` route.

    Warning:
        Currently, this implementation exposes user database credentials as plain text in
        POST body once and stores it within a bearer token as Base64 encoded for
        subsequent requests. That is how the server is able to submit queries on user's
        behalf. Due to this, it is required that remote hosts expose the server only
        under HTTPS to ensure end-to-end encryption. Sending passwords in plain text over
        HTTPS in POST request body is common and utilized by companies such as GitHub
        (2021) and Chase Bank (2021). On server side, there is no caching, logging, or
        storage of received passwords or tokens and thus available only briefly in
        memory. This means the primary vulnerable point is client side. Users should be
        responsible with their passwords and bearer tokens treating them as
        one-in-the-same. Be aware that if your client system happens to be compromised,
        a bad actor could monitor your outgoing network requests and capture/log your
        credentials. However, in such a terrible scenario, a bad actor would not only
        collect credentials for your DataJoint database but also other sites such as
        github.com, chase.com, etc. Please be responsible and vigilant with credentials
        and tokens on client side systems. Improvements to the above strategy is
        currently being tracked in https://github.com/datajoint/pharus/issues/82.

    Returns:
        Function output is an encoded JWT if successful, otherwise return error message

    ## POST /login

    Route to generate an authentication token.

    ### Example request:

    ```http
    POST /login HTTP/1.1
    Host: fakeservices.datajoint.io
    Accept: application/json

    {
        "databaseAddress": "tutorial-db.datajoint.io",
        "username": "user1",
        "password": "password1"
    }
    ```

    ### Example successful response:

    ```http
    HTTP/1.1 200 OK
    Vary: Accept
    Content-Type: application/json

    {
        "jwt": "<token>"
    }
    ```

    ### Example unexpected response:

    ```http
    HTTP/1.1 500 Internal Server Error
    Vary: Accept
    Content-Type: text/plain

    400 Bad Request: The browser (or proxy) sent a request that this server could not
        understand.
    ```

    #### Response Headers
    * Content-Type: text/plain, application/json

    #### Status Codes
    * 200 OK: No error.
    * 500 Internal Server Error: Unexpected error encountered.
        Returns the error message as a string.
    """
    if request.method == "POST":
        # Try to login in with the database connection info, if true then create jwt key
        try:
            if "database_host" in request.args:
                # Oidc token exchange

                body = {
                    "grant_type": "authorization_code",
                    "code": request.args["code"],
                    "code_verifier": environ.get("PHARUS_OIDC_CODE_VERIFIER"),
                    "client_id": environ.get("PHARUS_OIDC_CLIENT_ID"),
                    "redirect_uri": environ.get("PHARUS_OIDC_REDIRECT_URI"),
                }
                headers = {
                    "Content-Type": "application/x-www-form-urlencoded",
                }
                auth = HTTPBasicAuth(
                    environ.get("PHARUS_OIDC_CLIENT_ID"),
                    environ.get("PHARUS_OIDC_CLIENT_SECRET"),
                )
                result = requests.post(
                    environ.get("PHARUS_OIDC_TOKEN_URL"),
                    data=body,
                    headers=headers,
                    auth=auth,
                )
                auth_info = dict(
                    jwt=result.json()["access_token"], id=result.json()["id_token"]
                )
                time.sleep(1)
                connect_creds = {
                    "databaseAddress": request.args["database_host"],
                    "username": jwt.decode(
                        auth_info["jwt"],
                        crypto_serialization.load_der_public_key(
                            b64decode(environ.get("PHARUS_OIDC_PUBLIC_KEY").encode())
                        ),
                        algorithms="RS256",
                        options=dict(verify_aud=False),
                    )[environ.get("PHARUS_OIDC_SUBJECT_KEY")],
                    "password": auth_info["jwt"],
                }
            else:  # Database login
                # Generate JWT key and send it back
                auth_info = dict(
                    jwt=jwt.encode(
                        request.json, environ["PHARUS_PRIVATE_KEY"], algorithm="RS256"
                    )
                )
                connect_creds = request.json
            if connect_creds.keys() < {"databaseAddress", "username", "password"}:
                return dict(error="Invalid Request, check headers and/or json body")
            try:
                dj.Connection(
                    host=connect_creds["databaseAddress"],
                    user=connect_creds["username"],
                    password=connect_creds["password"],
                )
            except pymysql.err.OperationalError as e:
                if (
                    (root_host := environ.get("DJ_HOST"))
                    and (root_user := environ.get("DJ_ROOT_USER"))
                    and (root_password := environ.get("DJ_ROOT_PASS"))
                ):
                    dj.Connection(
                        host=root_host,
                        user=root_user,
                        password=root_password,
                    ).query("FLUSH PRIVILEGES")
                    dj.Connection(
                        host=connect_creds["databaseAddress"],
                        user=connect_creds["username"],
                        password=connect_creds["password"],
                    )
                else:
                    raise e
            return dict(**auth_info)
        except Exception:
            return traceback.format_exc(), 500

schema(connection)

Handler for /schema route.

Parameters:

Name Type Description Default
connection Connection

User's DataJoint connection object

required

Returns:

Type Description
dict

If successful, then sends back a list of schema names; otherwise, returns an error.

GET /schema

Route to get a list of schemas.

Example request:
1
2
3
GET /schema HTTP/1.1
Host: fakeservices.datajoint.io
Authorization: Bearer <token>
Example successful response:
1
2
3
4
5
6
7
8
9
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json

{
    "schemaNames": [
        "alpha_company"
    ]
}
Example unexpected response:
1
2
3
4
5
6
HTTP/1.1 500 Internal Server Error
Vary: Accept
Content-Type: text/plain

400 Bad Request: The browser (or proxy) sent a request that this server could not
    understand.
Request Headers
  • Authorization: Bearer <OAuth2_token>
Response Headers
  • Content-Type: text/plain, application/json
Status Codes
  • 200 OK: No error.
  • 500 Internal Server Error: Unexpected error encountered. Returns the error message as a string.
Source code in pharus/server.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
@app.route(f"{environ.get('PHARUS_PREFIX', '')}/schema", methods=["GET"])
@protected_route
def schema(connection: dj.Connection) -> dict:
    """
    Handler for ``/schema`` route.

    Args:
        connection (dj.Connection): User's DataJoint connection object

    Returns:
        If successful, then sends back a list of schema names; otherwise, returns an error.

    ## GET /schema

    Route to get a list of schemas.

    ### Example request:

    ```http
    GET /schema HTTP/1.1
    Host: fakeservices.datajoint.io
    Authorization: Bearer <token>
    ```

    ### Example successful response:

    ```http
    HTTP/1.1 200 OK
    Vary: Accept
    Content-Type: application/json

    {
        "schemaNames": [
            "alpha_company"
        ]
    }
    ```

    ### Example unexpected response:

    ```http
    HTTP/1.1 500 Internal Server Error
    Vary: Accept
    Content-Type: text/plain

    400 Bad Request: The browser (or proxy) sent a request that this server could not
        understand.
    ```

    #### Request Headers
    * Authorization: Bearer <OAuth2_token\>

    #### Response Headers
    * Content-Type: text/plain, application/json

    #### Status Codes
    * 200 OK: No error.
    * 500 Internal Server Error: Unexpected error encountered.
        Returns the error message as a string.
    """

    if request.method in {"GET", "HEAD"}:
        # Get all the schemas
        try:
            schemas_name = _DJConnector._list_schemas(connection)
            return dict(schemaNames=schemas_name)
        except Exception:
            return traceback.format_exc(), 500

table(connection, schema_name)

Handler for /schema/{schema_name}/table route.

Parameters:

Name Type Description Default
connection Connection

User's DataJoint connection object

required
schema_name str

Schema name.

required

Returns:

Type Description
dict

If successful, then sends back a list of table names; otherwise, returns an error.

GET /schema/{schema_name}/table

Route to get tables within a schema.

Example request:
1
2
3
GET /schema/alpha_company/table HTTP/1.1
Host: fakeservices.datajoint.io
Authorization: Bearer <token>
Example successful response:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json

{
    "tableTypes": {
        "computed": [],
        "imported": [],
        "lookup": [
            "Employee"
        ],
        "manual": [
            "Computer"
        ],
        "part": []
    }
}
Example unexpected response:
1
2
3
4
5
6
HTTP/1.1 500 Internal Server Error
Vary: Accept
Content-Type: text/plain

400 Bad Request: The browser (or proxy) sent a request that this server could not
    understand.
Query Parameters
  • schema_name: Schema name.
Request Headers
  • Authorization: Bearer <OAuth2_token>
Response Headers
  • Content-Type: text/plain, application/json
Status Codes
  • 200 OK: No error.
  • 500 Internal Server Error: Unexpected error encountered. Returns the error message as a string.
Source code in pharus/server.py
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
@app.route(
    f"{environ.get('PHARUS_PREFIX', '')}/schema/<schema_name>/table", methods=["GET"]
)
@protected_route
def table(
    connection: dj.Connection,
    schema_name: str,
) -> dict:
    """
    Handler for ``/schema/{schema_name}/table`` route.

    Args:
        connection (dj.Connection): User's DataJoint connection object
        schema_name (str): Schema name.

    Returns:
        If successful, then sends back a list of table names; otherwise, returns an error.

    ## GET /schema/{schema_name}/table

    Route to get tables within a schema.

    ### Example request:

    ```http
    GET /schema/alpha_company/table HTTP/1.1
    Host: fakeservices.datajoint.io
    Authorization: Bearer <token>
    ```

    ### Example successful response:

    ```http
    HTTP/1.1 200 OK
    Vary: Accept
    Content-Type: application/json

    {
        "tableTypes": {
            "computed": [],
            "imported": [],
            "lookup": [
                "Employee"
            ],
            "manual": [
                "Computer"
            ],
            "part": []
        }
    }
    ```

    ### Example unexpected response:

    ```http
    HTTP/1.1 500 Internal Server Error
    Vary: Accept
    Content-Type: text/plain

    400 Bad Request: The browser (or proxy) sent a request that this server could not
        understand.
    ```

    #### Query Parameters
    * schema_name: Schema name.

    #### Request Headers
    * Authorization: Bearer <OAuth2_token\>

    #### Response Headers
    * Content-Type: text/plain, application/json

    #### Status Codes
    * 200 OK: No error.
    * 500 Internal Server Error: Unexpected error encountered.
        Returns the error message as a string.
    """
    if request.method in {"GET", "HEAD"}:
        try:
            tables_dict_list = _DJConnector._list_tables(connection, schema_name)
            return dict(tableTypes=tables_dict_list)
        except Exception:
            return traceback.format_exc(), 500

record(connection, schema_name, table_name)

Handler for /schema/{schema_name}/table/{table_name}/record route.

Parameters:

Name Type Description Default
connection Connection

User's DataJoint connection object

required
schema_name str

Schema name.

required
table_name str

Table name.

required

Returns:

Type Description
Union[dict, str, tuple]

If successful, then sends back the desired operation based on the HTTP method; otherwise, returns an error.

GET /schema/{schema_name}/table/{table_name}/record

Route to fetch records.

Example request:
1
2
3
4
5
GET /schema/alpha_company/table/Computer/record?limit=1&page=2&order=computer_id%20DESC&
    restriction=W3siYXR0cmlidXRlTmFtZSI6ICJjb21wdXRlcl9tZW1vcnkiLCAib3BlcmF0aW9uIjogIj49I
    iwgInZhbHVlIjogMTZ9XQo= HTTP/1.1
Host: fakeservices.datajoint.io
Authorization: Bearer <token>
Example successful response:
 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
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json

{
    "recordHeader": [
        "computer_id",
        "computer_serial",
        "computer_brand",
        "computer_built",
        "computer_processor",
        "computer_memory",
        "computer_weight",
        "computer_cost",
        "computer_preowned",
        "computer_purchased",
        "computer_updates",
        "computer_accessories"
    ],
    "records": [
        [
            "4e41491a-86d5-4af7-a013-89bde75528bd",
            "DJS1JA17G",
            "Dell",
            1590364800,
            2.2,
            16,
            4.4,
            "700.99",
            0,
            1603181061,
            null,
            "=BLOB="
        ]
    ],
    "totalCount": 2
}
Example unexpected response:
1
2
3
4
5
6
HTTP/1.1 500 Internal Server Error
Vary: Accept
Content-Type: text/plain

400 Bad Request: The browser (or proxy) sent a request that this server could
    not understand.
Query Parameters
  • schema_name: Schema name.
  • table_name: Table name.
  • limit: Limit of how many records per page. Defaults to 1000.
  • page: Page requested. Defaults to 1.
  • order: Sort order. Defaults to KEY ASC.
  • restriction: Base64-encoded AND sequence of restrictions. For example, you could restrict as [{"attributeName": "computer_memory", "operation": ">=", "value": 16}] with this param set as W3siYXR0cmlidXRlTmFtZSI6ICJjb21wdXRlcl9tZW1vcnkiLCAib3BlcmF0a W9uIjogIj49IiwgInZhbHVlIjogMTZ9XQo=. Defaults to no restriction.
Request Headers
  • Authorization: Bearer <OAuth2_token>
Response Headers
  • Content-Type: text/plain, application/json
Status Codes
  • 200 OK: No error.
  • 500 Internal Server Error: Unexpected error encountered. Returns the error message as a string.

POST /schema/{schema_name}/table/{table_name}/record

Route to insert a record. Omitted attributes utilize the default if set.

Example request:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
POST /schema/alpha_company/table/Computer/record HTTP/1.1
Host: fakeservices.datajoint.io
Accept: application/json
Authorization: Bearer <token>

{
    "records": [
        {
            "computer_id": "ffffffff-86d5-4af7-a013-89bde75528bd",
            "computer_serial": "ZYXWVEISJ",
            "computer_brand": "HP",
            "computer_built": "2021-01-01",
            "computer_processor": 2.7,
            "computer_memory": 32,
            "computer_weight": 3.7,
            "computer_cost": 599.99,
            "computer_preowned": 0,
            "computer_purchased": "2021-02-01 13:00:00",
            "computer_updates": 0
        }
    ]
}
Example successful response:
1
2
3
4
5
6
7
HTTP/1.1 200 OK
Vary: Accept
Content-Type: text/plain

{
    "response": "Insert Successful"
}
Example unexpected response:
1
2
3
4
5
6
HTTP/1.1 500 Internal Server Error
Vary: Accept
Content-Type: text/plain

400 Bad Request: The browser (or proxy) sent a request that this server could
    not understand.
Request Headers
  • Authorization: Bearer <OAuth2_token>
Response Headers
  • Content-Type: text/plain
Status Codes
  • 200 OK: No error.
  • 500 Internal Server Error: Unexpected error encountered. Returns the error message as a string.

PATCH /schema/{schema_name}/table/{table_name}/record

Route to update a record. Omitted attributes utilize the default if set.

Example request:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
PATCH /schema/alpha_company/table/Computer/record HTTP/1.1
Host: fakeservices.datajoint.io
Accept: application/json
Authorization: Bearer <token>

{
    "records": [
        {
            "computer_id": "ffffffff-86d5-4af7-a013-89bde75528bd",
            "computer_serial": "ZYXWVEISJ",
            "computer_brand": "HP",
            "computer_built": "2021-01-01",
            "computer_processor": 2.7,
            "computer_memory": 32,
            "computer_weight": 3.7,
            "computer_cost": 601.01,
            "computer_preowned": 0,
            "computer_purchased": "2021-02-01 13:00:00",
            "computer_updates": 0
        }
    ]
}
Example successful response:
1
2
3
4
5
6
7
HTTP/1.1 200 OK
Vary: Accept
Content-Type: text/plain

{
    "response": "Update Successful"
}
Example unexpected response:
1
2
3
4
5
6
HTTP/1.1 500 Internal Server Error
Vary: Accept
Content-Type: text/plain

400 Bad Request: The browser (or proxy) sent a request that this server could
    not understand.
Request Headers
  • Authorization: Bearer <OAuth2_token>
Response Headers
  • Content-Type: text/plain
Status Codes
  • 200 OK: No error.
  • 500 Internal Server Error: Unexpected error encountered. Returns the error message as a string.

DELETE /schema/{schema_name}/table/{table_name}/record

Route to delete a specific record.

Example request:
1
2
3
4
5
DELETE /schema/alpha_company/table/Computer/record?cascade=false&restriction=
    W3siYXR0cmlidXRlTmFtZSI6ICJjb21wdXRlcl9tZW1vcnkiLCAib3BlcmF0aW9uIjogIj49IiwgInZhbHVlI
    jogMTZ9XQo= HTTP/1.1
Host: fakeservices.datajoint.io
Authorization: Bearer <token>
Example successful response:
1
2
3
4
5
6
7
HTTP/1.1 200 OK
Vary: Accept
Content-Type: text/plain

{
    "response": "Delete Successful"
}
Example conflict response:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
HTTP/1.1 409 Conflict
Vary: Accept
Content-Type: application/json

{
    "error": "IntegrityError",
    "error_msg": "Cannot delete or update a parent row: a foreign key
        constraint fails (`alpha_company`.`#employee`, CONSTRAINT
        `#employee_ibfk_1` FOREIGN KEY (`computer_id`) REFERENCES `computer`
        (`computer_id`) ON DELETE RESTRICT ON UPDATE CASCADE",
    "child_schema": "alpha_company",
    "child_table": "Employee"
}
Example unexpected response:
1
2
3
4
5
6
HTTP/1.1 500 Internal Server Error
Vary: Accept
Content-Type: text/plain

400 Bad Request: The browser (or proxy) sent a request that this server could
    not understand.
Query Parameters
  • cascade: Enable cascading delete. Accepts true or false. Defaults to false.
  • restriction: Base64-encoded AND sequence of restrictions. For example, you could restrict as [{"attributeName": "computer_memory", "operation": ">=", "value": 16}] with this param set as W3siYXR0cmlidXRlTmFtZSI6ICJjb21wdXRlcl9tZW1vcnkiLCAib3BlcmF0aW9uIjogIj49 IiwgInZhbHVlIjogMTZ9XQo=. Defaults to no restriction.
Request Headers
  • Authorization: Bearer <OAuth2_token>
Response Headers
  • Content-Type: text/plain, application/json
Status Codes
  • 200 OK: No error.
  • 409 Conflict: Attempting to delete a record with dependents while cascade set to false.
  • 500 Internal Server Error: Unexpected error encountered. Returns the error message as a string.
Source code in pharus/server.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
@app.route(
    f"{environ.get('PHARUS_PREFIX', '')}/schema/<schema_name>/table/<table_name>/record",
    methods=["GET", "POST", "PATCH", "DELETE"],
)
@protected_route
def record(
    connection: dj.Connection,
    schema_name: str,
    table_name: str,
) -> Union[dict, str, tuple]:
    (
        """
    Handler for ``/schema/{schema_name}/table/{table_name}/record`` route.

    Args:
        connection (dj.Connection): User's DataJoint connection object
        schema_name (str): Schema name.
        table_name (str): Table name.

    Returns:
        If successful, then sends back the desired operation based on the HTTP method;
            otherwise, returns an error.

    ## GET /schema/{schema_name}/table/{table_name}/record

    Route to fetch records.

    ### Example request:

    ```http
    GET /schema/alpha_company/table/Computer/record?limit=1&page=2&order=computer_id%20DESC&
        restriction=W3siYXR0cmlidXRlTmFtZSI6ICJjb21wdXRlcl9tZW1vcnkiLCAib3BlcmF0aW9uIjogIj49I
        iwgInZhbHVlIjogMTZ9XQo= HTTP/1.1
    Host: fakeservices.datajoint.io
    Authorization: Bearer <token>
    ```

    ### Example successful response:

    ```http
    HTTP/1.1 200 OK
    Vary: Accept
    Content-Type: application/json

    {
        "recordHeader": [
            "computer_id",
            "computer_serial",
            "computer_brand",
            "computer_built",
            "computer_processor",
            "computer_memory",
            "computer_weight",
            "computer_cost",
            "computer_preowned",
            "computer_purchased",
            "computer_updates",
            "computer_accessories"
        ],
        "records": [
            [
                "4e41491a-86d5-4af7-a013-89bde75528bd",
                "DJS1JA17G",
                "Dell",
                1590364800,
                2.2,
                16,
                4.4,
                "700.99",
                0,
                1603181061,
                null,
                "=BLOB="
            ]
        ],
        "totalCount": 2
    }
    ```

    ### Example unexpected response:

    ```http
    HTTP/1.1 500 Internal Server Error
    Vary: Accept
    Content-Type: text/plain

    400 Bad Request: The browser (or proxy) sent a request that this server could
        not understand.
    ```

    #### Query Parameters
    * schema_name: Schema name.
    * table_name: Table name.
    * limit: Limit of how many records per page. Defaults to `1000`.
    * page: Page requested. Defaults to `1`.
    * order: Sort order. Defaults to `KEY ASC`.
    * restriction: Base64-encoded `AND` sequence of restrictions. For example, you could
        restrict as `[{"attributeName": "computer_memory", "operation": ">=", "value": 16}]`
        with this param set as `W3siYXR0cmlidXRlTmFtZSI6ICJjb21wdXRlcl9tZW1vcnkiLCAib3BlcmF0a
        W9uIjogIj49IiwgInZhbHVlIjogMTZ9XQo=`. Defaults to no restriction.

    #### Request Headers
    * Authorization: Bearer <OAuth2_token\>

    #### Response Headers
    * Content-Type: text/plain, application/json

    #### Status Codes
    * 200 OK: No error.
    * 500 Internal Server Error: Unexpected error encountered. Returns the error message as a
        string.

    ## POST /schema/{schema_name}/table/{table_name}/record

    Route to insert a record. Omitted attributes utilize the default if set.

    ### Example request:

    ```http
    POST /schema/alpha_company/table/Computer/record HTTP/1.1
    Host: fakeservices.datajoint.io
    Accept: application/json
    Authorization: Bearer <token>

    {
        "records": [
            {
                "computer_id": "ffffffff-86d5-4af7-a013-89bde75528bd",
                "computer_serial": "ZYXWVEISJ",
                "computer_brand": "HP",
                "computer_built": "2021-01-01",
                "computer_processor": 2.7,
                "computer_memory": 32,
                "computer_weight": 3.7,
                "computer_cost": 599.99,
                "computer_preowned": 0,
                "computer_purchased": "2021-02-01 13:00:00",
                "computer_updates": 0
            }
        ]
    }
    ```

    ### Example successful response:

    ```http
    HTTP/1.1 200 OK
    Vary: Accept
    Content-Type: text/plain

    {
        "response": "Insert Successful"
    }
    ```

    ### Example unexpected response:

    ```http
    HTTP/1.1 500 Internal Server Error
    Vary: Accept
    Content-Type: text/plain

    400 Bad Request: The browser (or proxy) sent a request that this server could
        not understand.
    ```

    #### Request Headers
    * Authorization: Bearer <OAuth2_token\>

    #### Response Headers
    * Content-Type: text/plain

    #### Status Codes
    * 200 OK: No error.
    * 500 Internal Server Error: Unexpected error encountered. Returns the error message as a
        string.

    ## PATCH /schema/{schema_name}/table/{table_name}/record

    Route to update a record. Omitted attributes utilize the default if set.

    ### Example request:

    ```http
    PATCH /schema/alpha_company/table/Computer/record HTTP/1.1
    Host: fakeservices.datajoint.io
    Accept: application/json
    Authorization: Bearer <token>

    {
        "records": [
            {
                "computer_id": "ffffffff-86d5-4af7-a013-89bde75528bd",
                "computer_serial": "ZYXWVEISJ",
                "computer_brand": "HP",
                "computer_built": "2021-01-01",
                "computer_processor": 2.7,
                "computer_memory": 32,
                "computer_weight": 3.7,
                "computer_cost": 601.01,
                "computer_preowned": 0,
                "computer_purchased": "2021-02-01 13:00:00",
                "computer_updates": 0
            }
        ]
    }
    ```

    ### Example successful response:

    ```http
    HTTP/1.1 200 OK
    Vary: Accept
    Content-Type: text/plain

    {
        "response": "Update Successful"
    }
    ```

    ### Example unexpected response:

    ```http
    HTTP/1.1 500 Internal Server Error
    Vary: Accept
    Content-Type: text/plain

    400 Bad Request: The browser (or proxy) sent a request that this server could
        not understand.
    ```

    #### Request Headers
    * Authorization: Bearer <OAuth2_token\>

    #### Response Headers
    * Content-Type: text/plain

    #### Status Codes
    * 200 OK: No error.
    * 500 Internal Server Error: Unexpected error encountered. Returns the error message as a
        string.

    ## DELETE /schema/{schema_name}/table/{table_name}/record

    Route to delete a specific record.

    ### Example request:

    ```http
    DELETE /schema/alpha_company/table/Computer/record?cascade=false&restriction=
        W3siYXR0cmlidXRlTmFtZSI6ICJjb21wdXRlcl9tZW1vcnkiLCAib3BlcmF0aW9uIjogIj49IiwgInZhbHVlI
        jogMTZ9XQo= HTTP/1.1
    Host: fakeservices.datajoint.io
    Authorization: Bearer <token>
    ```

    ### Example successful response:

    ```http
    HTTP/1.1 200 OK
    Vary: Accept
    Content-Type: text/plain

    {
        "response": "Delete Successful"
    }
    ```

    ### Example conflict response:

    ```http
    HTTP/1.1 409 Conflict
    Vary: Accept
    Content-Type: application/json

    {
        "error": "IntegrityError",
        "error_msg": "Cannot delete or update a parent row: a foreign key
            constraint fails (`alpha_company`.`#employee`, CONSTRAINT
            `#employee_ibfk_1` FOREIGN KEY (`computer_id`) REFERENCES `computer`
            (`computer_id`) ON DELETE RESTRICT ON UPDATE CASCADE",
        "child_schema": "alpha_company",
        "child_table": "Employee"
    }
    ```

    ### Example unexpected response:

    ```http
    HTTP/1.1 500 Internal Server Error
    Vary: Accept
    Content-Type: text/plain

    400 Bad Request: The browser (or proxy) sent a request that this server could
        not understand.
    ```

    #### Query Parameters
    * cascade: Enable cascading delete. Accepts ``true`` or ``false``. Defaults to
        ``false``.
    * restriction: Base64-encoded ``AND`` sequence of restrictions. For example,
        you could restrict as ``[{"attributeName": "computer_memory", "operation": ">=",
        "value": 16}]`` with this param set as
        ``W3siYXR0cmlidXRlTmFtZSI6ICJjb21wdXRlcl9tZW1vcnkiLCAib3BlcmF0aW9uIjogIj49
        IiwgInZhbHVlIjogMTZ9XQo=``. Defaults to no restriction.

    #### Request Headers
    * Authorization: Bearer <OAuth2_token\>

    #### Response Headers
    * Content-Type: text/plain, application/json

    #### Status Codes
    * 200 OK: No error.
    * 409 Conflict: Attempting to delete a record with dependents while ``cascade``
        set to ``false``.
    * 500 Internal Server Error: Unexpected error encountered. Returns the error message as a
        string.

    """
    )
    if request.method in {"GET", "HEAD"}:
        try:
            schema_virtual_module = dj.VirtualModule(
                schema_name, schema_name, connection=connection
            )

            # Get table object from name
            dj_table = _DJConnector._get_table_object(schema_virtual_module, table_name)

            record_header, table_tuples, total_count = _DJConnector._fetch_records(
                query=dj_table,
                **{
                    k: int(v) for k, v in request.args.items() if k in ("limit", "page")
                },
                **{
                    k: loads(b64decode(v.encode("utf-8")).decode("utf-8"))
                    for k, v in request.args.items()
                    if k == "restriction"
                },
                **{k: v.split(",") for k, v in request.args.items() if k == "order"},
            )
            return dict(
                recordHeader=record_header, records=table_tuples, totalCount=total_count
            )
        except Exception:
            return traceback.format_exc(), 500
    elif request.method == "POST":
        try:
            _DJConnector._insert_tuple(
                connection, schema_name, table_name, request.json["records"]
            )
            return {"response": "Insert Successful"}
        except Exception:
            return traceback.format_exc(), 500
    elif request.method == "PATCH":
        try:
            _DJConnector._update_tuple(
                connection, schema_name, table_name, request.json["records"]
            )
            return {"response": "Update Successful"}
        except Exception:
            return traceback.format_exc(), 500
    elif request.method == "DELETE":
        try:
            _DJConnector._delete_records(
                connection,
                schema_name,
                table_name,
                **{
                    k: loads(b64decode(v.encode("utf-8")).decode("utf-8"))
                    for k, v in request.args.items()
                    if k == "restriction"
                },
                **{
                    k: v.lower() == "true"
                    for k, v in request.args.items()
                    if k == "cascade"
                },
            )
            return {"response": "Delete Successful"}
        except IntegrityError as e:
            match = foreign_key_error_regexp.match(e.args[0])
            return (
                dict(
                    error=e.__class__.__name__,
                    errorMessage=str(e),
                    childSchema=match.group("child").split(".")[0][1:-1],
                    childTable=to_camel_case(match.group("child").split(".")[1][1:-1]),
                ),
                409,
            )
        except Exception:
            return traceback.format_exc(), 500

definition(connection, schema_name, table_name)

Handler for /schema/{schema_name}/table/{table_name}/definition route.

Parameters:

Name Type Description Default
connection Connection

User's DataJoint connection object

required
schema_name str

Schema name.

required
table_name str

Table name.

required

Returns:

Type Description
str

If successful, then sends back the definition for the table; otherwise, returns an error.

GET /schema/{schema_name}/table/{table_name}/definition

Route to get DataJoint table definition.

Example request:
1
2
3
GET /schema/alpha_company/table/Computer/definition HTTP/1.1
Host: fakeservices.datajoint.io
Authorization: Bearer <token>
Example successful response:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
HTTP/1.1 200 OK
Vary: Accept
Content-Type: text/plain

# Computers that belong to the company
computer_id          : uuid                      # unique id
---
computer_serial="ABC101" : varchar(9)            # manufacturer serial number
computer_brand       : enum('HP','Dell')         # manufacturer brand
computer_built       : date                      # manufactured date
computer_processor   : double                    # processing power in GHz
computer_memory      : int                       # RAM in GB
computer_weight      : float                     # weight in lbs
computer_cost        : decimal(6,2)              # purchased price
computer_preowned    : tinyint                   # purchased as new or used
computer_purchased   : datetime                  # purchased date and time
computer_updates=null : time                     # scheduled daily update timeslot
computer_accessories=null : longblob             # included additional accessories
Example unexpected response:
1
2
3
4
5
6
HTTP/1.1 500 Internal Server Error
Vary: Accept
Content-Type: text/plain

400 Bad Request: The browser (or proxy) sent a request that this server could not
    understand.
Request Headers
  • Authorization: Bearer <OAuth2_token>
Response Headers
  • Content-Type: text/plain
Status Codes
  • 200 OK: No error.
  • 500 Internal Server Error: Unexpected error encountered. Returns the error message as a string.
Source code in pharus/server.py
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
@app.route(
    f"{environ.get('PHARUS_PREFIX', '')}/schema/<schema_name>/table/<table_name>/definition",
    methods=["GET"],
)
@protected_route
def definition(
    connection: dj.Connection,
    schema_name: str,
    table_name: str,
) -> str:
    """
    Handler for ``/schema/{schema_name}/table/{table_name}/definition`` route.

    Args:
        connection (dj.Connection): User's DataJoint connection object
        schema_name (str): Schema name.
        table_name (str): Table name.

    Returns:
        If successful, then sends back the definition for the table; otherwise,
            returns an error.

    ## GET /schema/{schema_name}/table/{table_name}/definition

    Route to get DataJoint table definition.

    ### Example request:

    ```http
    GET /schema/alpha_company/table/Computer/definition HTTP/1.1
    Host: fakeservices.datajoint.io
    Authorization: Bearer <token>
    ```

    ### Example successful response:

    ```http
    HTTP/1.1 200 OK
    Vary: Accept
    Content-Type: text/plain

    # Computers that belong to the company
    computer_id          : uuid                      # unique id
    ---
    computer_serial="ABC101" : varchar(9)            # manufacturer serial number
    computer_brand       : enum('HP','Dell')         # manufacturer brand
    computer_built       : date                      # manufactured date
    computer_processor   : double                    # processing power in GHz
    computer_memory      : int                       # RAM in GB
    computer_weight      : float                     # weight in lbs
    computer_cost        : decimal(6,2)              # purchased price
    computer_preowned    : tinyint                   # purchased as new or used
    computer_purchased   : datetime                  # purchased date and time
    computer_updates=null : time                     # scheduled daily update timeslot
    computer_accessories=null : longblob             # included additional accessories
    ```

    ### Example unexpected response:

    ```http
    HTTP/1.1 500 Internal Server Error
    Vary: Accept
    Content-Type: text/plain

    400 Bad Request: The browser (or proxy) sent a request that this server could not
        understand.
    ```

    #### Request Headers
    * Authorization: Bearer <OAuth2_token\>

    #### Response Headers
    * Content-Type: text/plain

    #### Status Codes
    * 200 OK: No error.
    * 500 Internal Server Error: Unexpected error encountered. Returns the error message as a
        string.
    """

    if request.method in {"GET", "HEAD"}:
        try:
            table_definition = _DJConnector._get_table_definition(
                connection, schema_name, table_name
            )
            return table_definition
        except Exception:
            return traceback.format_exc(), 500

attribute(connection, schema_name, table_name)

Handler for /schema/{schema_name}/table/{table_name}/attribute route.

Parameters:

Name Type Description Default
connection Connection

User's DataJoint connection object

required
schema_name str

Schema name.

required
table_name str

Table name.

required

Returns:

Type Description
dict

If successful, then sends back a dictionary of table attributes; otherwise, returns an error.

GET /schema/{schema_name}/table/{table_name}/attribute

Route to get metadata on table attributes.

Example request:
1
2
3
GET /schema/alpha_company/table/Computer/attribute HTTP/1.1
Host: fakeservices.datajoint.io
Authorization: Bearer <token>
Example successful response:
  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
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json

{
    "attributeHeader": [
        "name",
        "type",
        "nullable",
        "default",
        "autoincrement"
    ],
    "attributes": {
        "primary": [
            [
                "computer_id",
                "uuid",
                false,
                null,
                false
            ]
        ],
        "secondary": [
            [
                "computer_serial",
                "varchar(9)",
                false,
                ""ABC101"",
                false
            ],
            [
                "computer_brand",
                "enum('HP','Dell')",
                false,
                null,
                false
            ],
            [
                "computer_built",
                "date",
                false,
                null,
                false
            ],
            [
                "computer_processor",
                "double",
                false,
                null,
                false
            ],
            [
                "computer_memory",
                "int",
                false,
                null,
                false
            ],
            [
                "computer_weight",
                "float",
                false,
                null,
                false
            ],
            [
                "computer_cost",
                "decimal(6,2)",
                false,
                null,
                false
            ],
            [
                "computer_preowned",
                "tinyint",
                false,
                null,
                false
            ],
            [
                "computer_purchased",
                "datetime",
                false,
                null,
                false
            ],
            [
                "computer_updates",
                "time",
                true,
                "null",
                false
            ],
            [
                "computer_accessories",
                "longblob",
                true,
                "null",
                false
            ]
        ]
    }
}
Example unexpected response:
1
2
3
4
5
6
HTTP/1.1 500 Internal Server Error
Vary: Accept
Content-Type: text/plain

400 Bad Request: The browser (or proxy) sent a request that this server could not
    understand.
Request Headers
  • Authorization: Bearer <OAuth2_token>
Response Headers
  • Content-Type: text/plain, application/json
Status Codes
  • 200 OK: No error.
  • 500 Internal Server Error: Unexpected error encountered. Returns the error message as a string.
Source code in pharus/server.py
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
@app.route(
    f"{environ.get('PHARUS_PREFIX', '')}/schema/<schema_name>/table/<table_name>/attribute",
    methods=["GET"],
)
@protected_route
def attribute(
    connection: dj.Connection,
    schema_name: str,
    table_name: str,
) -> dict:
    """
    Handler for ``/schema/{schema_name}/table/{table_name}/attribute`` route.

    Args:
        connection (dj.Connection): User's DataJoint connection object
        schema_name (str): Schema name.
        table_name (str): Table name.

    Returns:
        If successful, then sends back a dictionary of table attributes; otherwise,
            returns an error.

    ## GET /schema/{schema_name}/table/{table_name}/attribute

    Route to get metadata on table attributes.

    ### Example request:

    ```http
    GET /schema/alpha_company/table/Computer/attribute HTTP/1.1
    Host: fakeservices.datajoint.io
    Authorization: Bearer <token>
    ```

    ### Example successful response:

    ```http
    HTTP/1.1 200 OK
    Vary: Accept
    Content-Type: application/json

    {
        "attributeHeader": [
            "name",
            "type",
            "nullable",
            "default",
            "autoincrement"
        ],
        "attributes": {
            "primary": [
                [
                    "computer_id",
                    "uuid",
                    false,
                    null,
                    false
                ]
            ],
            "secondary": [
                [
                    "computer_serial",
                    "varchar(9)",
                    false,
                    ""ABC101"",
                    false
                ],
                [
                    "computer_brand",
                    "enum('HP','Dell')",
                    false,
                    null,
                    false
                ],
                [
                    "computer_built",
                    "date",
                    false,
                    null,
                    false
                ],
                [
                    "computer_processor",
                    "double",
                    false,
                    null,
                    false
                ],
                [
                    "computer_memory",
                    "int",
                    false,
                    null,
                    false
                ],
                [
                    "computer_weight",
                    "float",
                    false,
                    null,
                    false
                ],
                [
                    "computer_cost",
                    "decimal(6,2)",
                    false,
                    null,
                    false
                ],
                [
                    "computer_preowned",
                    "tinyint",
                    false,
                    null,
                    false
                ],
                [
                    "computer_purchased",
                    "datetime",
                    false,
                    null,
                    false
                ],
                [
                    "computer_updates",
                    "time",
                    true,
                    "null",
                    false
                ],
                [
                    "computer_accessories",
                    "longblob",
                    true,
                    "null",
                    false
                ]
            ]
        }
    }
    ```

    ### Example unexpected response:

    ```http
    HTTP/1.1 500 Internal Server Error
    Vary: Accept
    Content-Type: text/plain

    400 Bad Request: The browser (or proxy) sent a request that this server could not
        understand.
    ```

    #### Request Headers
    * Authorization: Bearer <OAuth2_token\>

    #### Response Headers
    * Content-Type: text/plain, application/json

    #### Status Codes
    * 200 OK: No error.
    * 500 Internal Server Error: Unexpected error encountered. Returns the error message as a
        string.
    """

    if request.method in {"GET", "HEAD"}:
        try:
            local_values = locals()
            local_values[schema_name] = dj.VirtualModule(
                schema_name, schema_name, connection=connection
            )

            # Get table object from name
            dj_table = _DJConnector._get_table_object(
                local_values[schema_name], table_name
            )

            attributes_meta = _DJConnector._get_attributes(dj_table)
            return dict(
                attributeHeaders=attributes_meta["attribute_headers"],
                attributes=attributes_meta["attributes"],
            )
        except Exception:
            return traceback.format_exc(), 500

dependency(connection, schema_name, table_name)

Handler for /schema/{schema_name}/table/{table_name}/dependency route.

Parameters:

Name Type Description Default
connection Connection

User's DataJoint connection object

required
schema_name str

Schema name.

required
table_name str

Table name.

required

Returns:

Type Description
dict

If successful, then sends back a list of dependencies; otherwise, returns an error.

GET /schema/{schema_name}/table/{table_name}/dependency

Route to get the metadata in relation to the dependent records associated with a restricted subset of a table.

Example request:
1
2
3
4
5
GET /schema/alpha_company/table/Computer/dependency?restriction=
    W3siYXR0cmlidXRlTmFtZSI6ICJjb21wdXRlcl9tZW1vcnkiLCAib3BlcmF0aW9uIjogIj49IiwgInZ=
    HTTP/1.1
Host: fakeservices.datajoint.io
Authorization: Bearer <token>
Example successful response:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
HTTP/1.1 200 OK
Vary: Accept
Content-Type: application/json

{
    "dependencies": [
        {
            "accessible": true,
            "count": 2,
            "schema": "alpha_company",
            "table": "computer"
        },
        {
            "accessible": true,
            "count": 2,
            "schema": "alpha_company",
            "table": "#employee"
        }
    ]
}
Example unexpected response:
1
2
3
4
5
6
HTTP/1.1 500 Internal Server Error
Vary: Accept
Content-Type: text/plain

400 Bad Request: The browser (or proxy) sent a request that this server could not
    understand.
Query Parameters
  • schema_name: Schema name.
  • table_name: Table name.
  • restriction: Base64-encoded AND sequence of restrictions. For example, you could restrict as [{"attributeName": "computer_memory", "operation": ">=", "value": 16}] with this param set as W3siYXR0cmlidXRlTmFtZSI6ICJjb21wdXRlcl9tZW1vcnkiLCAib3BlcmF0aW9uIjogIj49IiwgInZ=. Defaults to no restriction.
Request Headers
  • Authorization: Bearer <OAuth2_token>
Response Headers
  • Content-Type: text/plain, application/json
Status Codes
  • 200 OK: No error.
  • 500 Internal Server Error: Unexpected error encountered. Returns the error message as a string.
Source code in pharus/server.py
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
@app.route(
    f"{environ.get('PHARUS_PREFIX', '')}/schema/<schema_name>/table/<table_name>/dependency",
    methods=["GET"],
)
@protected_route
def dependency(
    connection: dj.Connection,
    schema_name: str,
    table_name: str,
) -> dict:
    (
        """
    Handler for ``/schema/{schema_name}/table/{table_name}/dependency`` route.

    Args:
        connection (dj.Connection): User's DataJoint connection object
        schema_name (str): Schema name.
        table_name (str): Table name.

    Returns:
        If successful, then sends back a list of dependencies; otherwise, returns an error.

    ## GET /schema/{schema_name}/table/{table_name}/dependency

    Route to get the metadata in relation to the dependent records associated with a
        restricted subset of a table.

    ### Example request:

    ```http
    GET /schema/alpha_company/table/Computer/dependency?restriction=
        W3siYXR0cmlidXRlTmFtZSI6ICJjb21wdXRlcl9tZW1vcnkiLCAib3BlcmF0aW9uIjogIj49IiwgInZ=
        HTTP/1.1
    Host: fakeservices.datajoint.io
    Authorization: Bearer <token>
    ```

    ### Example successful response:

    ```http
    HTTP/1.1 200 OK
    Vary: Accept
    Content-Type: application/json

    {
        "dependencies": [
            {
                "accessible": true,
                "count": 2,
                "schema": "alpha_company",
                "table": "computer"
            },
            {
                "accessible": true,
                "count": 2,
                "schema": "alpha_company",
                "table": "#employee"
            }
        ]
    }
    ```

    ### Example unexpected response:

    ```http
    HTTP/1.1 500 Internal Server Error
    Vary: Accept
    Content-Type: text/plain

    400 Bad Request: The browser (or proxy) sent a request that this server could not
        understand.
    ```

    #### Query Parameters
    * schema_name: Schema name.
    * table_name: Table name.
    * restriction: Base64-encoded ``AND`` sequence of restrictions. For example, you could
        restrict as ``[{"attributeName": "computer_memory", "operation": ">=", "value": 16}]``
        with this param set as
        ``W3siYXR0cmlidXRlTmFtZSI6ICJjb21wdXRlcl9tZW1vcnkiLCAib3BlcmF0aW9uIjogIj49IiwgInZ=``.
        Defaults to no restriction.

    #### Request Headers
    * Authorization: Bearer <OAuth2_token\>

    #### Response Headers
    * Content-Type: text/plain, application/json

    #### Status Codes
    * 200 OK: No error.
    * 500 Internal Server Error: Unexpected error encountered. Returns the error message as a
        string.
    """
    )
    if request.method in {"GET", "HEAD"}:
        # Get dependencies
        try:
            dependencies = _DJConnector._record_dependency(
                connection,
                schema_name,
                table_name,
                loads(
                    b64decode(request.args.get("restriction").encode("utf-8")).decode(
                        "utf-8"
                    )
                ),
            )
            return dict(dependencies=dependencies)
        except Exception:
            return traceback.format_exc(), 500

run()

Starts API server.

Source code in pharus/server.py
1263
1264
1265
1266
1267
def run():
    """
    Starts API server.
    """
    app.run(host="0.0.0.0", port=environ.get("PHARUS_PORT", 5000), threaded=False)