- Saved searches
- Use saved searches to filter your results more quickly
- dharmesh143/rest_api_php
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
- Платформа для быстрого создания RESTful API
- api-platform
- apigility
- Моё решение
- Saved searches
- Use saved searches to filter your results more quickly
- License
- shahbaz17/php-rest-api
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
This is REST API example developed in PHP
dharmesh143/rest_api_php
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
This is REST API example developed in PHP
Step 1 : you need to create MySQL Database to make it working Step 2 : Import SQL file in your database under SQL/rest_api.sql Two tables are created just to create demo application.
Step 3 : Update database connection setting in config\database.php
// specify your own database credentials private $host = "localhost"; private $db_name = "rest_api"; private $username = "root"; private $password = ""; public $conn;
Step 4 : Now you are ready to access data using REST API.
API will return formate in Json.
1.0 Read Products 1.1 Product Object 1.2 Create «read.php» file 1.3 Add Product «read()» method 1.4 Output : http://localhost/api/product/read.php
2.0 Create Product 2.1 Create create.php file 2.2 Product create() method
3.0 Read One Product 3.1 Create read_one.php file 3.2 Product readOne() method 3.3 Output http://localhost/api/product/read_one.php?id=60
4.0 Update product 4.1 Create “update.php” file 4.2 Product update() method
5.0 Delete Product 5.1 Create “delete.php” file 5.2 Product delete() method
5.0 Search Products 5.1 Create «search.php» file 5.2 Create «search()» method 5.3 Output : http://localhost/api/product/search.php?s=shirt
6.0 Paginate Products 6.1 Create «read_paging.php» file 6.2 Create «core.php» file 6.3 Create «readPaging()» method 6.4 Create «count()» method 6.5 Get «paging» array 6.6 Output
11.0 Read Categories 11.1 Category object 11.2 Create «read.php» file 11.3 Category «read()» method 11.4 Output : http://localhost/api/category/read.php
About
This is REST API example developed in PHP
Платформа для быстрого создания RESTful API
За последние несколько лет мне пришлось создать много API на PHP. Большая часть из них была RESTful. Первый раз это было интересно — часы обсуждения формата ответа, содержимого ошибок, вариантов авторизации и прочей романтики. Во второй раз не покидало чувство дежавю. На третий раз уже было понятно — надо что-то менять…
Ну и на четвёртый раз, когда передо мной поставили задачу создания API, параллельно разработке основного проекта, я приступил к созданию универсальной платформы для создания API в котором уже будут решены все «главные» вопросы:
- Формат ответа (в том числе и ошибок)
- Форматирование даты
- Ведение документации
- Авторизации и аутентификации
- Валидация запросов
- и многое другое
api-platform
Сайт: api-platform.com
Очень мощное решение. Сделано на основе php-фреймворка Symfony. Есть всё что нужно и даже больше. Наверно, для тех кто любит программирование через конфигурации и Symfony, это то что нужно. Увы я не отношусь к этой категории.
apigility
Сайт: apigility.org
Не менее мощное решение. На этот раз на основе фреймворка Zend. Это даже какая-то CMS для создания API, причём и RESTful и RPC. Наверно, для тех кто любит программирование с помощью мышки, это то что нужно. Увы я и к этой категории не отношусь.
Есть и другие решения, вот неплохая подборочка.
Но в итоге ничего милого моему сердцу выбрать не удалось. Зато удалось сформировать несколько принципов и требований к будущему проекту:
- Код, а не аннотации и конфигурации
- Никаких UI
- Создание полностью готового API одной командой
- Автогенерация документации. Желательно по коду, а не из аннотаций
- Простота
- Минимум велосипедов
Моё решение
Америки я не открыл. Просто взял хорошие компоненты, собрал их вместе, написал весь необходимый boilerplate-код для работы и собрал composer проект.
Краеугольный камень — это стандарт представления jsonapi. С помощью него решены почти все «холиварные» вопросы. Мне осталось только принять решение по формату запросов с фильтрацией, сортировкой и постраничной навигацией. За вывод отвечает пакет json-api от neomerx (Кстати, не так давно он тоже собрал свой api starter pack).
В качестве основы я выбрал Slim3. Грамотно спроектированный, быстрый, легко расширяемый и простой.
Для работы с БД ORM Eloquent. Удобная, сравнительно быстрая и простая.
Работу с правами и контролем доступа построил на основе Zend ACL. На удивление простой пакет для работы с правами.
Документацию генерирую по комментариям написанным в коде с помощью ApiDocJS. Почему не Swagger? Пробовал и его, но мне apidoc понравился больше.
Код размещён на github, проект доступен на packagist.
Сразу после установки у вас будет полностью готовое API со всем необходимым. Буду рад, если кто-то применит пакет в работе. Я уже успел сделать 1 проект на нём (+ тот проект, который делал параллельно с bootstrapi) — полёт нормальный.
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
License
shahbaz17/php-rest-api
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Build a Simple REST API in PHP
This example shows how to build a simple REST API in core PHP.
Clone this project with the following commands:
git clone https://github.com/shahbaz17/php-rest-api.git cd php-rest-api
Configure the application
Create the database and user for the project.
mysql -u root -p CREATE DATABASE blog CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; CREATE USER 'rest_api_user'@'localhost' identified by 'rest_api_password'; GRANT ALL on blog.* to 'rest_api_user'@'localhost'; quit
mysql -u rest_api_user -p; // Enter your password use blog; CREATE TABLE `post` ( `id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(255) NOT NULL, `body` text NOT NULL, `author` varchar(255), `author_picture` varchar(255), `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`) );
Copy .env.example to .env file and enter your database deatils.
Install the project dependencies and start the PHP server:
php -S localhost:8000 -t api
API | CRUD | Description |
---|---|---|
GET /posts | READ | Get all the Posts from post table |
GET /post/ | READ | Get a single Post from post table |
POST /post | CREATE | Create a Post and insert into post table |
PUT /post/ | UPDATE | Update the Post in post table |
DELETE /post/ | DELETE | Delete a Post from post table |
Test the API endpoints using Postman.