PHPMaker supports REST API that enables you to perform CRUD
(Create, Read, Update and Delete) for the tables in the generated web application.
You can issue the request to the API (e.g. via JavaScript code), get the response as JSON (JavaScript Object Notation),
interpret and present the result as you like it. The default path for the API request is "api" under the generated application (i.e. <mysite>/api).
Note In this article we assume the API is at <mysite>/api so the URL of the API is /api/, if you change the API to a different folder, you need to change the URL in the following examples accordingly.
API Actions
The REST API is implemented on the basis of the list, view, add, edit and delete pages supported for each table selected for generation.
The basic supported API actions are add (Create), list / view (Read),
edit (Update), delete (Delete), login (Authenticate User, if Security is enabled) and
file (Get file content).
From PHPMaker 2023 onwards, the **export** API action is also supported. You can export a table or report to a file and retrieve it later using the **export** API. See [Export API](export.html) for details.
**Note** If the supported method for an API action is POST, the API not only supports form data but also JSON data (except for file upload). If you use JSON, make sure you
1. Set the content type as ``application/json``,
1. Use [Full JSON grammar](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON#full_json_grammar), such as using double quotes (NOT single quotes) to quote strings and property names,
1. Use UTF-8 encoded string so it can be decoded by [json_decode()](https://www.php.net/manual/en/function.json-decode.php).
The standard exchange of information with the API is shown in the following examples (using the "cars" table of the demo database for demonstration).
Example 1 - Get a record by key (view action)
HTTP Request
GET /api/view/cars/1
Accept: application/json
HTTP Response
200 OK
Example 2 - Create a record (add action)
HTTP Request
POST /api/add/cars
Trademark=1&...
Accept: application/json
HTTP Response (success) 200 OK
HTTP Response (failure) 200 OK
Example 3 - Export and retrieve exported file (export action)
1. Export file and get file ID
HTTP Request
GET /api/export/excel/cars?filename=...&save=1&output=0
Accept: application/json
HTTP Response
200 OK 2. Retrieve exported file content by file ID
HTTP Request
GET /api/export/575879b9-9c87-45de-9403-8c7e753981e5
HTTP Response
200 OK
Exported file content is returned.
Supported API Actions
Note If you enable Use Swagger UI for API (see Tools -> Advanced Settings), you can test these actions with Swagger UI at http://mysite/basepath/swagger/.
POST/api/login
GET /api/login
POST/api/login
If the user uses the REST API from an external client (not within the generated web application), the user needs to login first. The login API authenticates an user by JWT token, see Authenticate user with JWT below for details.
If specified, the JWT is valid only for the specified permission. See table below of the list of permission types and values.
Note the permission can only be a subset of the permission of the login user.
Permission Types and Values
See [Permissions](http://localhost:3000/#/securitysetup.html?id=permissions) for the list of permission types and values. To specify a combination of permission types, add the values together. For example, for List + Export, use 8 + 1024 (i.e. 1032)
Successful response
Note When testing in Swagger UI, after loggiing in, you need to click the Authorize button and enter "Bearer <JsonWebToken>" to authorize yourself before testing other actions.
Field name. Optional, sort by the specified field, requires activating the Sort setting in List page.
ordertype(query)
Sort ascending ('ASC') or descending ('DESC'). Optional, requires activating the Sortsetting in List page.
<fieldname>(query)
Search specified field by value. Optional, requires activating the Advanced/Extended Search setting in List page.
Successful response Failed response
GET/api/export/{type}/{table}/{key}
GET/api/export/{id}
GET/api/export/search
GET/api/export/{type}/{table}/{key}
Export records from a table, e.g.
/api/export/excel/cars
Parameters
type(path)
Export type, e.g. 'excel', 'word', 'pdf', 'html'. Required.
table(path)
Table name. Required.
key(query)
Primary key of a record. Optional, for retrieving a singe record (from the View page).
page(query)
Page number. Optional.
recperpage(query)
Records per page. Optional.
filename(query)
File name of the exported file. Optional, for overriding the default file name only.
save(query)
Save the exported file on the server. Value: 0 or 1. Optional, default is 0.
output(query)
Output the exported file on the server. Value: 0 or 1. Optional, default is 1, i.e. output the file directly.
Successful response
Export with output=0:
Export without "save" parameter, or output=1:
<Exported file content>
Failed response
See failed response for list
GET/api/export/{id}
Get exported file from id, e.g.
/api/export/575879b9-9c87-45de-9403-8c7e753981e5
Parameters
id(path)
File ID of the exported file. Required.
filename(query)
File name of the exported file. Optional, for overriding the default file name only.
Successful response
<Exported file content>
Failed response
See failed response for list
GET/api/export/search
Search exported files, e.g.
/api/export/search/?limit=1
Parameters
limit(query)
Latest count of exported files (Integer)
type(query)
Export type, e.g. 'excel', 'word', 'pdf', 'html'
tablename(query)
Table name
filename(query)
File name
datetime(query)
Date/Time
output(query)
Output the exported file on the server. Value: 0 or 1. Optional, default is 1, i.e. output the file directly.
Successful response
Search with output=0:
Search without "output" parameter, or output=1:
<Exported file content>
Note: If there is more than one file after search, the output will be a zipped file of the exported files.
Failed response
See failed response for list
GET/api/view/{table}/{key}
Get single record by key, e.g.
/api/view/cars/1
Parameters
table(path)
Table name. Required.
key(path)
Primary key of the record. Required.
Successful response Failed response
See failed response for list
POST/api/add/{table}
Insert a new record, e.g.
/api/add/cars
Trademark=1&...
Parameters
table(path)
Table name. Required.
<fieldname>
Field value to be inserted. Required.
Successful response Failed response
See failed response for list
POST/api/register
Register a new user in the user table, e.g.
/api/register
Username=newuser&...
Parameters
<fieldname>
Field value to be inserted. Required.
Successful response Failed response
See failed response for list
POST/api/edit/{table}/{key}
Update an existing record by key, eg.
/api/edit/cars/1
Trademark=2&...
Parameters
table(path)
Table name. Required.
key(path)
Primary key of the record. Required.
<fieldname>
Field value to be updated. Required.
Successful response Failed response
See failed response for list
GET /api/delete/{table}/{key}
POST /api/delete/{table}
GET /api/delete/{table}/{key}
Delete an existing record by key, e.g.
/api/delete/cars/1
Parameters
table(path)
Table name. Required.
key(path)
Primary key of the record to be deleted. Required.
POST /api/delete/{table}
Delete multiple records by keys, e.g.
/api/delete/cars
key_m[]=1&key_m[]=2&...
Parameters
table(path)
Table name. Required.
key_m[]
Primary keys of records to be deleted. Required.
Note If composite key, <FieldValue> is comma separated values.
Successful response Failed response
See failed response for list
GET/api/file/{table}/{field}/{key}
GET/api/file/{table}/{field}/{key}
Get file info by primary, e.g.
/api/file/employees/Photo/1
Parameters
table(path)
Table name. Required.
field(path)
Field name. Required.
key(path)
Primary key of the record. Required.
Note If composite key, when testing in Swagger UI, enter {key} as comma separated values.
Successful response
For blob field (e.g. Picture field in cars table), binary content of file field with the correct content type.
For string field (e.g. Photo field in employees table), JSON response of file locations:
If file path is encrypted:
then you can use the second file action to get the file content.
Failed response
Empty response
POST/api/upload
Upload files, e.g.
/api/upload
See example below.
Parameters
body
Form data. Required.
Successful response
JSON response of file token and file info: Failed response
GET/api/permissions/{userLevelID}
POST /api/permissions/{userLevelID}
GET/api/permissions/{userLevelID}
Get permissions, e.g.
/api/permissions/1
Parameters
userLevelID(path)
User Level ID. Required.
POST /api/permissions/{userLevelID}
Update permissions, e.g.
/api/permissions/1
{ "cars": 264, ... }
Parameters
userLevelID(path)
User Level ID. Required.
body(body)
Permissions in JSON format, e.g. { "<Table1>": <Permission1>, "<Table2>": <Permission2>, ... }. Required.
See the list of Permission Types and Values in Login API above.
Successful response
Get permissions:
Update permission:
Failed response
Authenticate User with JWT (JSON Web Token)
REST API is stateless. Each API request is independent of each other and no session data is stored in the server
to record the current state of the API requests.
Notes
To access protected resources from the API,
you need to authenticate the user first by getting a JSON Web Token (JWT) using the login action,
then you must pass the JWT as an authentication header (e.g. X-Authorization, see the advanced setting **API JWT authorization header** below) in subsequent API requests. Otherwise, you will get a 401 Unauthorized response if the API action is protected.
Each JWT has a limited timespan, so you may need to re-authenticate the user again once the token has expired.
To understand more about JWT, please visit [Introduction to JSON Web Tokens](https://jwt.io/introduction/).
The following JavaScript shows how to get a protected resource from the API by JWT. Authenticate the user first by
clicking the login button. Then click the Get order record button to get the order record
which is a protected resource.
Upload Files
To upload files, you can use upload action (see above). You can upload file(s) by HTML 5, e.g.
If you want to let the user select multiple files, simply use the multiple attribute on the input element and add [] to the name:
Notes
When the user selects file(s), the files property of the input element is a FileList object containing File objects representing the files selected by the user.
If file uploading is successful, you will get successful response (see above) with a file token, then you can use the file token as the field value of your field for add or edit actions.
Uploading multiple files to a BLOB field is NOT supported.
Create Your Own API Action
Beside the built-in API actions, you can add your own API actions by Api_Action server event (see Server Events and Client Scripts).
Example 1 - Hello world
The user can now access the URL /api/hello/John to get the response text
"Hello John".
Notes
Make sure you return a Psr\Http\Message\ResponseInterface object in your route callback.
See Request and Response object for details about the $request and the $response arguments of the callback function.
Example 2 - Get product by name
The product data can now be accessed using the following JavaScript:
Note See Returning JSON for more details about returning JSON data from callback function.
Advanced Settings
You can customize the following settings for REST API in Advanced Settings.