Skip to content

mrxdev-git/php_rest_api

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

77 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Data Export API

This project is a simple, read-only REST API designed to export e-commerce data (such as products, categories, and features) from a database in a structured JSON format.

Project Structure

The project follows a standard MVC-like pattern:

.
├── bin/                  # Command-line scripts
│   └── generate-token.php  # Script to generate API tokens
├── config/               # Configuration files
│   ├── auth.php          # API token storage (add to .gitignore)
│   └── routes.php        # API route definitions
├── public/               # Public web root
│   └── index.php         # Main application entry point
├── src/                  # Application source code
│   ├── Controller/       # Request handlers
│   ├── Database/         # Database connection logic
│   ├── Middleware/       # Request middleware (e.g., Auth)
│   ├── Model/            # Database query logic
│   ├── Response/         # Response formatting
│   └── System/           # Core application system
└── composer.json         # Project dependencies

Configuration

This app uses environment variables to set up database credentials. To initialize environment variables, copy the .env.example file to .env and fill in the database connection details.

Note: The .env file is included in .gitignore and should not be committed to version control.** .env file example

DB_HOST=localhost
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=

Authentication

All API endpoints (except for the root /) are protected and require token-based authentication.

To authenticate, you must provide a valid API token as a GET query parameter named api_token in your request URL.

URL Format:

http://your-api-domain.com/endpoint?api_token=YOUR_SECRET_TOKEN

Requests with a missing or invalid token will receive a 401 Unauthorized response.

Generating an API Token

A command-line script is provided to generate a new, secure API token. This script will automatically replace the first token in your config/auth.php file.

To run it, execute the following command from the project root:

chmod +x bin/generate-token.php
./bin/generate-token.php

The new token will be printed to the console.

Available Endpoints

The following endpoints are available:

  • GET /

    • Description: A public landing page that provides information about the API.
    • Authentication: Not required.
  • GET /categories

    • Description: Retrieves a list of all available categories.
    • Authentication: Required.
  • GET /categories/count

    • Description: Retrieves the total number of categories.
    • Authentication: Required.
  • GET /products

    • Description: Retrieves a list of all available products.
    • Authentication: Required.
  • GET /products/count

    • Description: Retrieves the total number of products.
    • Authentication: Required.
  • GET /features

    • Description: Retrieves a list of all available product features.
    • Authentication: Required.
  • GET /features/count

    • Description: Retrieves the total number of product features.
    • Authentication: Required.

Example Request

Here is an example of how to fetch the list of products using curl:

# Replace YOUR_SECRET_TOKEN with the token generated by the script
curl -X GET "http://your-api-domain.com/products?api_token=YOUR_SECRET_TOKEN"

Example Success Response (/products):

{

  "data": [
    {
      "id": "222",
      "name": "Модульный автоматический выключатель e.industrial.mcb.100.1.C10, 1 р, 10А, С, 10кА, e-next",
      "status": "1",
      "price": "0.0000",
      "url": "modulnyi-avtomaticheskii-vycliuchatel-eindustrialmcb1001c10-1-r-10a-s-10ka",
      "description": "<p>Купить <strong>автоматический однополюсный выключатель e-next 10 ампер<\/strong>. Цена автоматов а Украине.<br>Данное устройство предназначено для защиты электрической сети от перегрузок, коротких замыканий и прочих нежелательных происшествий. Автоматический выключатель производится в прочном полимерном корпусе белого цвета, а корпус защищает конструкцию от различных внешних воздействий, повреждений и прочего. Доставка товаров осуществляется транспортными компаниями в любые регионы  Украины в течении 2-3 рабочих дней с момента окончательного оформления заказа. Для получения подробной информации свяжитесь с персоналом нашей компании. При регулярных заказах вы получите персональные скидки на все группы продукции, а также партнерские условия сотрудничества. <br><\/p><p>Купить или заказать такой выключатель можно в Запорожье или любом другом городе Украины.<\/p>",
      "sku_id": "48934",
      "currency": "UAH",
      "sku": {
        "id": "48934",
        "name": "",
        "sku": "",
        "price": "0.0000",
        "purchase_price": "0.0000",
        "compare_price": "0.0000",
        "count": null,
        "available": "1"
      },
      "features": [],
      "category_ids": [
        "564"
      ],
      "images": []
    },
    {
      "id": "223",
      "name": "Модульный автоматический выключатель e.industrial.mcb.100.1.C16, 1 р, 16А, С, 10кА, E-next",
      "status": "1",
      "price": "0.0000",
      "url": "modulnyi-avtomaticheskii-vycliuchatel-eindustrialmcb1001c16-1-r-16a-s-10ka",
      "description": "<p><strong> Автоматический выключатель E-next 1п 16 А. <\/strong>Автоматические выключатели можно устанавливать как у себя в доме, так и в магазинах, школах, промышленных объектах, общественных учреждениях и прочих постройках. Такое устройство предотвратит возникновение опасных ситуаций, связанных с электрической сетью, спасет от перегрузок технику и не допустит приводящих к пожару коротких замыканий. Автоматические выключатели доставляются в закрытых коробках, которые предотвращают воздействие на устройство воды, солнца и прочих природных факторов. Сам автомат имеет длительный эксплуатационный период и рассчитан на помещения с высокой температурой, повышенной влажностью и прочими незначительными раздражителями. <\/p><p>Купить или заказать такой выключатель можно в Сумах или любом другом городе Украины.<\/p>",
      "sku_id": "48935",
      "currency": "UAH",
      "sku": {
        "id": "48935",
        "name": "",
        "sku": "",
        "price": "0.0000",
        "purchase_price": "0.0000",
        "compare_price": "0.0000",
        "count": null,
        "available": "1"
      },
      "features": [],
      "category_ids": [
        "564"
      ],
      "images": []
    }
  ]
}

Example Error Response (401 Unauthorized):

{
    "error": "Unauthorized"
}

About

Rest api server on php

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages