apituto
1.0.0
api_teste.sql ), I use the existing configurations within app/config/ for database configurations and for easy use permission of model and modelsmanager ;public/index.php (or the application bootstrap ), replacing the standard form of application I use the Micro() application that enables a rapid performance application and also allows the use of APIs ; | Get | Get ($ id) | Post | Put | Delete | |
|---|---|---|---|---|---|
| DATA | Returns all | Returns one | Insert new data | Changes existing data | Removes existing data |
After creating the project we must follow the following steps:
public/index.php Important use PhalconMvcMicro; and referenced the application as a micro application, $app = new Micro($di); ;app/config/config.php file;index.php we should use the following development skeleton: $app = new Micro($di);
// Utiliza a API e através do método GET, RETORNA TODOS OS DADOS.
$app->get(
"/api/dados",
function () use ($app) {
}
);
/*
* Utiliza a API e através do método GET, RETORNA APENAS UM DADO.
* Nota: Ele receberá como GET um ID que terá um tratamento através do ':[0-9]+'
* permitindo assim que o mesmo seja somente do tipo INTEIRO.
*/
$app->get(
"/api/dados/{id:[0-9]+}",
function ($id) use ($app) {
}
);
// Utiliza a API e através do método POST, INSERE UM NOVO DADO.
$app->post(
"/api/dados",
function () use ($app) {
}
);
// Utiliza a API e através do método PUT, ALTERA UM DADO EXISTENTE respeitando o tratamento do ID.
$app->put(
"/api/dados/{id:[0-9]+}",
function ($id) use ($app) {
}
);
// Utiliza a API e através do método DELETE, REMOVE UM DADO EXISTENTE respeitando o tratamento do ID.
$app->delete(
"/api/dados/{id:[0-9]+}",
function () {
}
);
$app->handle();
modelsManager that was created along with Micro Application we must use the PHQL created to be interpreted, after data returned we will use a data Array to store all data found in the query and finally we must codify our Array to send in JSON form. // Utiliza a API e através do método GET, RETORNA TODOS OS DADOS.
$app->get(
"/api/dados",
function () use ($app) {
$phql = "SELECT * FROM dados";
$dados = $app->modelsManager->executeQuery($phql);
$data = [];
foreach($dados as $dado){
$data[] = [
'id' => $dado->id,
'nome' => $dado->nome,
'criado' => $dado->criado
];
}
echo json_encode($data);
}
);
$id variable that will be passed to the API URL . The variable received undergoes a treatment using {id:[0-9]+} , where we determine its name followed by the type of data it can receive, in this case limiting the data only for integer data, so we can filter our phql query so that it only returns one specific data Array . /*
* Utiliza a API e através do método GET, RETORNA APENAS UM DADO.
* Nota: Ele receberá como GET um ID que terá um tratamento através do ':[0-9]+'
* permitindo assim que o mesmo seja somente do tipo INTEIRO.
*/
$app->get(
"/api/dados/{id:[0-9]+}",
function ($id) use ($app) {
$phql = "SELECT * FROM dados WHERE id = ".$id;
$dados = $app->modelsManager->executeQuery($phql);
$data = [];
foreach($dados as $dado){
$data[] = [
'id' => $dado->id,
'nome' => $dado->nome,
'criado' => $dado->criado
];
}
echo json_encode($data);
}
);
RESPONSE() to send the application status and also return the data that was saved. For this we must create a new Array to make our insertion, where it will receive the name data and created via post .Response() , which allows us to send status codes (such as 201, 404, 500, 401, 409 ).JSON content passing our status and the returned data from our model.Array and send an answer through JSON content by passing our status and all errors found. // Utiliza a API e através do método POST, INSERE UM NOVO DADO.
$app->post(
"/api/dados",
function () use ($app) {
$insert = [
'nome' => $app->request->getPost('nome'),
'criado' => ( ($app->request->getPost('criado')) ? $app->request->getPost('criado') : date('Y-m-d H:i:s') )
];
$phql = "INSERT INTO dados (nome, criado) VALUES ('".$insert['nome']."', '".$insert['criado']."')";
echo $phql;
$status = $app->modelsManager->executeQuery($phql);
// cria response
$response = new Response();
if($status->success() === true){
$response->setStatusCode(201, "Criado");
$dados = Dados::findFirstBynome($insert['nome']);
$response->setJsonContent(
[
'status' => "ok",
'data' => $dados
]
);
} else {
$response->setStatusCode(409, "Conflito");
$erros = [];
foreach ($status->getMessages() as $msg){
$erros[] = $msg->getMessage();
}
$response->setJsonContent(
[
'status' => "Erro",
'messages' => $erros
]
);
}
return $response;
}
);
$id variable to be used to modify a specific data and by sending our success message we will not send the changed data, and only the status messages are sent. // Utiliza a API e através do método PUT, ALTERA UM DADO EXISTENTE respeitando o tratamento do ID.
$app->put(
"/api/dados/{id:[0-9]+}",
function ($id) use ($app) {
$update = [
'id' => $id,
'nome' => $app->request->getPut('nome'),
'criado' => $app->request->getPut('criado')
];
$phql = "UPDATE dados.dados SET dados.nome = '".$update['nome']."', dados.criado = '".$update['criado']."' WHERE dados.id = ".$id;
$status = $app->modelsManager->executeQuery($phql);
// cria response
$response = new Response();
if($status->success() === true){
$response->setStatusCode(201, "Criado");
$dados = $dados = Dados::findFirst($update['id']);
$response->setJsonContent(
[
'status' => "ok",
'data' => $dados
]
);
} else {
$response->setStatusCode(409, "Conflito");
$erros = [];
foreach ($status->getMessages() as $msg){
$erros[] = $msg->getMessage();
}
$response->setJsonContent(
[
'status' => "Erro",
'messages' => $erros
]
);
}
return $response;
}
);
// Utiliza a API e através do método DELETE, REMOVE UM DADO EXISTENTE respeitando o tratamento do ID.
$app->delete(
"/api/dados/{id:[0-9]+}",
function () {
$phql = "DELETE FROM dados.dados WHERE dados.id = ".$id;
$status = $app->modelsManager->executeQuery($phql);
// cria response
$response = new Response();
if($status->success() === true){
$response->setJsonContent(
[
'status' => "ok"
]
);
} else {
$response->setStatusCode(409, "Conflito");
$erros = [];
foreach ($status->getMessages() as $msg){
$erros[] = $msg->getMessage();
}
$response->setJsonContent(
[
'status' => "Erro",
'messages' => $erros
]
);
}
return $response;
}
);
http://localhost/NOME_DO_PROJETO/api/NOME_DA_TABELA . .htaccess file data located at the root of the project to: RewriteRule ^$ NOME_DO_MICRO_APP/api/ [L]
RewriteRule (.*) NOME_DO_MICRO_APP/api/$1 [L]