Build a REST API with PHP and JsonSchema

This tutorial explains in detail how to build a REST API with PHP and JsonSchema. We will build a simple “todo” API where you can manage todo entries. At first we design the API. This step should be done independent of the language which you use to implement the API. For the implementation step we are using the PSX framework to develop the API.

Design

The first thing which you should do, when building an API, is to plan the design of the API. That means that you describe what endpoints are available and how the data of the request and response is structured. For our example we define two simple routes:

/todo
/todo/:todo_id
/todo
GET: Return collection of entities
POST: Insert new entity to the collection
/todo/:todo_id
GET: Return an entity
PUT: Replace the content of the entity
DELETE: Remove the entity
{
"title": "todo",
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"title": {
"type": "string"
},
"insertDate": {
"type": "string",
"format": "date-time"
}
}
}
{
"id": 1,
"title": "foo",
"insertDate": "2016–02–04T19:56:44Z"
}
{
"title": "collection",
"type": "object",
"properties": {
"entry": {
"type": "array",
"items": {
"$ref": "file:///entity.json"
}
}
}
}
{
"entry": [{
"id": 1,
"title": "foo",
"insertDate": "2016–02–04T19:56:44Z"
}]
}
{
"title": "message",
"type": "object",
"properties": {
"success": {
"type": "boolean"
},
"message": {
"type": "string"
}
}
}
{
"success": true,
"message": "Insert todo entry was successful"
}
/todo
GET:
Response: collection.json
POST:
Request: entity.json
Response: message.json
/todo/:todo_id
GET:
Response: entity.json
PUT:
Request: entity.json
Response: message.json
DELETE:
Response: message.json

Implementation

In the implementation phase we want to turn the defined specification into
working code. Therefor we are using the PSX framework. We checkout the sample project with the following composer command:

composer create-project psx/sample psx
cache/  <- contains temporary and cache files
public/ <- directory which is accessible from the web
src/ <- source folder for the PHP code
tests/ <- folder which contains unit tests
vendor/ <- contains all external PHP dependencies
[['ANY'], '/todo', App\Api\Todo\Collection::class],
[['ANY'], '/todo/:id', App\Api\Todo\Entity::class],
class Collection extends SchemaApiAbstract
{
/**
* @Inject
* @var \Doctrine\DBAL\Connection
*/
protected $connection;
}

I am a developer in the API space, currently working on Fusio an open source API management platform

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store