Coder Social home page Coder Social logo

manuelgil / rest-api-with-slim-php Goto Github PK

View Code? Open in Web Editor NEW
73.0 11.0 38.0 1014 KB

REST API with PHP Slim Framework 3 and MySQL

License: MIT License

PHP 65.91% TSQL 34.09%
rest restful rest-api restful-api slim slim-3 slim-framework slimphp slim-micro-framework restapi

rest-api-with-slim-php's Introduction

REST Api with Slim PHP

This API works with the same concept of social network of Fav Quote.

This is a simple REST Web Service which allow:

  • Post short text messages of no more than 120 characters
  • Bring a list with the latest published messages
  • Search for messages by your text
  • Delete a specific message by its id

๐Ÿšฅ Getting Started

This page will help you get started with this API.

Requirements

  • PHP 5.6
  • MySQL or MariaDB
  • Apache Server
  • Slim Framework v3

Installation

Copy this project

  1. Clone or Download this repository
  2. Unzip the archive if needed
  3. Copy the folder in the htdocs dir
  4. Start a Text Editor (Atom, Sublime, Visual Studio Code, Vim, etc)
  5. Add the project folder to the editor

Install the project

  1. Go to htdocs dir
  • Windows
$ cd /d C:\xampp\htdocs
  • Linux
$ cd /opt/lampp/htdocs
  • MAC
$ cd applications/mamp/htdocs
  1. Go to the project folder
$ cd REST-Api-with-Slim-PHP
  1. Install with composer
$ composer install

Or

$ sudo php composer.phar install

Create a database

Import the NETWORK SCHEMA DDL.sql file.

Import the NETWORK SCHEMA DML.sql file.

Or run the following SQL script

SET @OLD_AUTOCOMMIT=@@AUTOCOMMIT, AUTOCOMMIT=0;
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

START TRANSACTION;

-- -----------------------------------------------------
-- Schema NETWORK
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `NETWORK` DEFAULT CHARACTER SET utf8 ;
USE `NETWORK` ;

-- -----------------------------------------------------
-- Table `NETWORK`.`COUNTRIES`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `NETWORK`.`COUNTRIES` (
  `ID_COUNTRY` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `ISO` VARCHAR(2) NOT NULL,
  `COUNTRY` VARCHAR(80) NOT NULL,
  PRIMARY KEY (`ID_COUNTRY`))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Dumping data for table `NETWORK`.`COUNTRIES`
-- -----------------------------------------------------
INSERT INTO `NETWORK`.`COUNTRIES` (`ID_COUNTRY`, `ISO`, `COUNTRY`) VALUES
(1, 'AF', 'Afghanistan');

-- -----------------------------------------------------
-- Table `NETWORK`.`USERS`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `NETWORK`.`USERS` (
  `ID_USER` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `GUID` VARCHAR(20) NOT NULL,
  `TOKEN` VARCHAR(255) DEFAULT NULL,
  `USERNAME` VARCHAR(20) NOT NULL,
  `PASSWORD` VARCHAR(255) NOT NULL,
  `CREATED_AT` DATE NOT NULL,
  `STATUS` TINYINT(1) NOT NULL DEFAULT '0',
  `ID_COUNTRY` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`ID_USER`),
  UNIQUE INDEX `ID_USER_UNIQUE` (`ID_USER` ASC),
  UNIQUE INDEX `USER_UNIQUE` (`USERNAME` ASC),
  UNIQUE INDEX `GUID_UNIQUE` (`GUID` ASC),
  INDEX `fk_USERS_COUNTRIES1_idx` (`ID_COUNTRY` ASC),
  CONSTRAINT `fk_USERS_COUNTRIES1`
    FOREIGN KEY (`ID_COUNTRY`)
    REFERENCES `NETWORK`.`COUNTRIES` (`ID_COUNTRY`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Dumping data for table `NETWORK`.`USERS`
-- -----------------------------------------------------
INSERT INTO `users` (`ID_USER`, `GUID`, `TOKEN`, `USERNAME`, `PASSWORD`, `CREATED_AT`, `STATUS`, `ID_COUNTRY`) VALUES
(0, '5acff05a49592', NULL, 'ManuelGil', '', '2018-01-01', 1, 47),
(1, '5ba4524f296c3', NULL, 'testUser', '$2y$10$dRWUrwXE56p3zvEadmnMYeFivd6aU9BfGb4LXsmf5p.xQlkTAX/V6', '2018-01-01', 1, 1);

-- -----------------------------------------------------
-- Table `NETWORK`.`QUOTES`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `NETWORK`.`QUOTES` (
  `ID_QUOTE` INT UNSIGNED NOT NULL AUTO_INCREMENT,
  `QUOTE` VARCHAR(120) NOT NULL,
  `POST_DATE` DATE NOT NULL,
  `POST_TIME` TIME NOT NULL,
  `LIKES` INT UNSIGNED NOT NULL DEFAULT 0,
  `ID_USER` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`ID_QUOTE`),
  UNIQUE INDEX `ID_QUOTE_UNIQUE` (`ID_QUOTE` ASC),
  INDEX `fk_QUOTES_USERS_idx` (`ID_USER` ASC),
  CONSTRAINT `fk_QUOTES_USERS`
    FOREIGN KEY (`ID_USER`)
    REFERENCES `NETWORK`.`USERS` (`ID_USER`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Dumping data for table `NETWORK`.`QUOTES`
-- -----------------------------------------------------
INSERT INTO `NETWORK`.`QUOTES` (`ID_QUOTE`, `QUOTE`, `POST_DATE`, `POST_TIME`, `LIKES`, `ID_USER`) VALUES
(0, 'Fav Quote is a Micro Social Network with PHP, MySQL, Bootstrap 3 and Vue.JS 2. It don\'t use classes or a php framework.', '2018-01-01', '00:00:00', 1, 0);

-- -----------------------------------------------------
-- Table `NETWORK`.`LIKES`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `NETWORK`.`LIKES` (
  `ID_USER` INT UNSIGNED NOT NULL,
  `ID_QUOTE` INT UNSIGNED NOT NULL,
  PRIMARY KEY (`ID_USER`, `ID_QUOTE`),
  INDEX `fk_LIKES_QUOTES1_idx` (`ID_QUOTE` ASC),
  CONSTRAINT `fk_LIKES_USERS1`
    FOREIGN KEY (`ID_USER`)
    REFERENCES `NETWORK`.`USERS` (`ID_USER`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_LIKES_QUOTES1`
    FOREIGN KEY (`ID_QUOTE`)
    REFERENCES `NETWORK`.`QUOTES` (`ID_QUOTE`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB;

COMMIT;

SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;

Configure the project

Copy the .env.example file and call it .env.

Change the database configuration in the new file.

๐ŸŽ Donate!

If you want to help me to continue this project, you might donate via PayPal.

Donate via PayPal

๐Ÿ“ฆ Deployment

Database Schema

Routes

  • get => /ping - This method is used for testing the api. e.g.:

    uri = http://localhost/REST-Api-with-Slim-PHP/public/webresources/mobile_app/ping

  • get => /login/{user}/{password} - This method gets a user into the database. e.g.:

    uri = http://localhost/REST-Api-with-Slim-PHP/public/webresources/mobile_app/login/testUser/testPwd

      parameters = [
        /** @var string $user - username */
        string	$user	=>	"testUser",
        /** @var string $password - password */
        string	$password	=>	"testPwd"
      ]
  • post => /register - This method sets a user into the database. e.g.:

    uri = http://localhost/REST-Api-with-Slim-PHP/public/webresources/mobile_app/register

      parameters = [
        /** @var string $user - username */
        string	$user	=>	"testUser",
        /** @var string $password - password */
        string	$password	=>	"testPwd",
        /** @var string $email - password */
        string	$email	=>	"[email protected]",
        /** @var int $country - country id */
        int	$country	=>	1
      ]
  • get => /validate/{user}/{token} - This method verify the user account. e.g.:

    uri = http://localhost/REST-Api-with-Slim-PHP/public/webresources/mobile_app/validate/testUser/326f0911657d94d0a48530058ca2a383

      parameters = [
        /** @var string $user - username */
        string	$user	=>	"testUser",
        /** @var string $token - token validation */
        string	$token	=>	"326f0911657d94d0a48530058ca2a383"
      ]
  • put => /update - This method sets a user into the database. e.g.:

    uri = http://localhost/REST-Api-with-Slim-PHP/public/webresources/mobile_app/update

      parameters = [
        /** @var int $country - country id */
        int	$country	=>	1
      ]
  • get => /verify - This method checks the token. e.g.:

    uri = http://localhost/REST-Api-with-Slim-PHP/public/webresources/mobile_app/verify

      headers = [
        /** @var string $authorization - JWT Authentication */
        string	$authorization	=>	"Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJoZWFkZXIiOnsiaWQiOjEsInVzZXIiOiJ0ZXN0VXNlciJ9LCJwYXlsb2FkIjp7ImlhdCI6IjIwMTktMDEtMDEgMDA6MDA6MDAiLCJleHAiOiIyMDIwLTAxLTAxIDAwOjAwOjAwIn19.RTTPlUqE--WMP9M28-oj7p8MhWdisuuhWBsioDa_bgY"
      ]
  • post => /post - This method publish short text messages of no more than 120 characters. e.g.:

    uri = http://localhost/REST-Api-with-Slim-PHP/public/webresources/mobile_app/post

      parameters = [
        /** @var string $quote - quote */
        string	$quote	=>	"test",
        /** @var int $id - user id */
        int	$id	=>	1
      ]
  • get => /list - This method list the latest published messages. e.g.:

    uri = http://localhost/REST-Api-with-Slim-PHP/public/webresources/mobile_app/list

  • get => /likes/{id} - get method - This method list the users for likes. e.g.:

    uri = http://localhost/REST-Api-with-Slim-PHP/public/webresources/mobile_app/likes/1

      parameters = [
        /** @var int $id - quote id */
        int	$id	=>	1
      ]
  • get => /search/{quote} - get method - This method searches for messages by your text. e.g.:

    uri = http://localhost/REST-Api-with-Slim-PHP/public/webresources/mobile_app/search/quote

      parameters = [
        /** @var string $quote - text search */
        string	$quote	=>	"quote"
      ]
  • delete => /delete - delete method - This method deletes a specific message by its id. e.g.:

    uri = http://localhost/REST-Api-with-Slim-PHP/public/webresources/mobile_app/delete

      parameters = [
        /** @var int $id - quote id */
        int	$id	=>	1
      ]

๐Ÿ’ฏ Running the tests

Use RestEasy or Postman app for testing.

For authentication you can generate a new JSON Web Token with the url login.

Put the parameters on a Query Parameter.

Put the token on an HTTP header called Authorization. e.g.:

  • Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJoZWFkZXIiOnsiaWQiOjEsInVzZXIiOiJ0ZXN0VXNlciJ9LCJwYXlsb2FkIjp7ImlhdCI6IjIwMTktMDEtMDEgMDA6MDA6MDAiLCJleHAiOiIyMDIwLTAxLTAxIDAwOjAwOjAwIn19.RTTPlUqE--WMP9M28-oj7p8MhWdisuuhWBsioDa_bgY
headers

Checks if the iat (issued at) and exp (expiration time) are correct in https://jwt.io/.

jwt

๐Ÿ”ง Built With

โ„น๏ธ Changelog

1.0.0.8 (10/16/2019)

  • Language: PHP
    Requirements:
    • PHP 5.6
    • MySQL or MariaDB
    • Apache Server
    Changes:
    • Fix responses
    • Implements caches

1.0.0.7 (01/24/2019)

  • Language: PHP
    Requirements:
    • PHP 5.6
    • MySQL or MariaDB
    • Apache Server
    Changes:
    • New update-user route
    • Update send mail function
    • Update verify Authentication Token function

1.0.0.6 (01/19/2019)

  • Language: PHP
    Requirements:
    • PHP 5.6
    • MySQL or MariaDB
    • Apache Server
    Changes:
    • Setting up CORS

1.0.0.5 (09/23/2018)

  • Language: PHP
    Requirements:
    • PHP 5.6
    • MySQL or MariaDB
    • Apache Server
    Changes:
    • PHPMail integration
    • Protection of files with .htaccess
    • Improvement in documentation

1.0.0.4 (08/12/2018)

  • Language: PHP
    Requirements:
    • PHP 5.6
    • MySQL or MariaDB
    • Apache Server
    Changes:
    • TODO: Unit testing (Removed)

1.0.0.3 (07/07/2018)

  • Language: PHP
    Requirements:
    • PHP 5.6
    • MySQL or MariaDB
    • Apache Server
    Changes:
    • DotEnv integration

1.0.0.2 (03/29/2018)

  • Language: PHP
    Requirements:
    • PHP 5.6
    • MySQL or MariaDB
    • Apache Server
    Changes:
    • Add a new table in database to save likes
    • Add 3 methods (ping, register, likes)
    • Add logger with Monolog
    • Add JSON file for installation with composer

1.0.0.1 (12/07/2017)

๐Ÿ‘“ Authors

See also the list of contributors who participated in this project.

๐Ÿ“ License

This API is licensed under the MIT License - see the MIT License for details.

rest-api-with-slim-php's People

Contributors

manuelgil avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rest-api-with-slim-php's Issues

Update doc with 'login' and 'register' api example to get clear idea

Hi,

First of all thank you for creating this clean starter project. I was experimenting with it, I installed and setup as per the instruction.

Currently when I hit an api lets say GET to http://localhost/REST-api-with-slim-PHP/public/webresources/mobile_app/ping

It send me response back pong which is correct.

But could you provide me example for LOGIN and REGISTER ?

I assume that for LOGIN it would be http://localhost/REST-api-with-slim-PHP/public/webresources/mobile_app/login/testUser/testPwd (without Bearer token)

I am getting blank response for above hit. Could you suggest me where I am doing wrong?

Installing in the correct folder ?

I have followed you advice given that is composer require slim/slim "^3.0"
Now when I go it create a folder called vendor and in it is slim with many slims folder like this /var/www/html/vendor/slim/slim/Slim so where to copy your codes ? Please advice ?

Cannot GET lists

Hi and thanks for the starter API.

I was able to register a new user and log in. I'm trying to GET lists but it's returning a 500 error. Here's the RAW response. Can you have a look?

Thanks!

HTTP GET http://domain/webresources/mobile_app/list/
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJoZWFkZXIiOnsiaWQiOiIzIiwidXNlciI6InRlc3RfdXNlciJ9LCJwYXlsb2FkIjp7ImlhdCI6IjIwMTgtMDQtMDYgMDE6NDY6MTkiLCJleHAiOiIyMDE4LTA0LTA2IDAzOjQ2OjE5In19.Wi31CNlssEg7bv0xAqJ7KMYUcONbGc-lbnBHb4VKKMQ
Host: domain


500 Internal Server Error
date: Fri, 06 Apr 2018 01:46:34 GMT
server: Apache/2.4.29 (Unix) PHP/7.1.14
connection: close
x-powered-by: PHP/7.1.14
content-length: 445
content-type: text/html;charset=UTF-8
<html><head><meta http-equiv='Content-Type' content='text/html; charset=utf-8'><title>Slim Application Error</title><style>body{margin:0;padding:30px;font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;}h1{margin:0;font-size:48px;font-weight:normal;line-height:48px;}strong{display:inline-block;width:65px;}</style></head><body><h1>Slim Application Error</h1><p>A website error has occurred. Sorry for the temporary inconvenience.</p></body></html>

Keep getting 401 unauthorized

Hi Manuel thanks for this API,
i succeded in installing and making calls but I keep getting a 401 error when I try methods that need the autentication token. Here's the screen...

issue_401

I enabled displayErrorDetails in the index, how can I debug this?

Slim 4 upgrade inquiry.

Hi
How is it going?
Any thoughts on updating to slim 4?
So, I hope you are always healthy and happy.

The value is incorrect in postman.

Hi.
When I run http: // localhost / public / webresources / mobile_app / verify, the result of "200 OK" is displayed in RestEasy.
However, when running in postman, the status is "401 Unauthorized".
What did I do wrong in postman?
please answer about my question.
Thank you :)

GET: http: // localhost / public / webResources / mobile_app / verify
Authorization
TYPE: BearerToken
Token: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJoZWFkZXIiOnsiaWQiOjEsInVzZXIiOiJ0ZXN0VXNlciJ9LCJwYXlsb2FkIjp7ImlhdCI6IjIwMTktMDEtMDEgMDA6MDA6MDAiLCJleHAiOiIyMDIwLTAxLTAxIDAwOjAwOjAwIn19.RTTPlUqE - WMP9M28-oj7p8MhWdisuuhWBsioDa_bgY

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.