[[oktatas:programozás:php:php_rest_api|< PHP REST API]] ====== PHP REST API mocking ====== * **Szerző:** Sallai András * Copyright (c) Sallai András, 2022 * [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]] * Web: http://szit.hu ===== Végpont ===== ^ Végpont ^^^ | products | GET | az összes terméket adja | ===== Egyszerűen tömbből ===== 1, "name"=>"vaj", "price"=>1.8 ], [ "id"=>2, "name"=>"kenyér", "price"=>0.8 ], [ "id"=>3, "name"=>"tej", "price"=>0.9 ] ]; $res = json_encode( $data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT ); echo $res; } A tömb egyszerűsített verzióját használtuk PHP-ban. Így is írhatjuk: $data = array( array( "id"=>1, "name"=>"vaj", "price"=>1.8 ), array( "id"=>2, "name"=>"kenyér", "price"=>0.8 ), array( "id"=>3, "name"=>"tej", "price"=>0.9 ) ); A product tulajdonság megadása: $data = [ "products" => [ [ "id"=>1, "name"=>"vaj", "price"=>1.8 ], [ "id"=>2, "name"=>"kenyér", "price"=>0.8 ], [ "id"=>3, "name"=>"tej", "price"=>0.9 ] ] ]; Ezek után csak a termékekre így hivatkozunk: $res = json_encode( $data['products'], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT ); $data = [ "products" => [ [ "id"=>1, "name"=>"vaj", "price"=>1.8 ], [ "id"=>2, "name"=>"kenyér", "price"=>0.8 ], [ "id"=>3, "name"=>"tej", "price"=>0.9 ] ], "customers" => [ ["id"=>1, "name"=>"Penge Béla", "city"=>"Szeged"], ["id"=>2, "name"=>"Ezres Irén", "city"=>"Szeged"], ["id"=>3, "name"=>"Látó Ervin", "city"=>"Szeged"], ] ]; ===== Egyszerűen JSON fájlból ===== [ { "id": 1, "name": "vaj", "price": 2 }, { "id": 2, "name": "kifli", "price": 0.7 }, { "id": 3, "name": "vaj", "price": 2 } ] ===== A products tulajdonsággal ===== { "products": [ { "id": 1, "name": "vaj", "price": 2 }, { "id": 2, "name": "kifli", "price": 0.7 }, { "id": 3, "name": "vaj", "price": 2 } ] } {'products'}, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT ); echo $res; } ===== Lehetséges JavaScript kliens ===== var url = 'http://localhost:3000/api/products'; fetch(url) .then(res => res.json()) .then(res => { console.log(res ); }); ==== Rendereléssel ==== Táblázat a HTML oldalon.
# Név Ár
const tableBody = document.querySelector('#tableBody'); var url = 'http://localhost:3000/api/products'; fetch(url) .then(res => res.json()) .then(res => { res.forEach(prod => { console.log(prod.name); let tr = document.createElement('tr'); let tdId = document.createElement('td'); let tdName = document.createElement('td'); let tdPrice = document.createElement('td'); tableBody.appendChild(tr); tr.appendChild(tdId); tr.appendChild(tdName); tr.appendChild(tdPrice); tdId.textContent = prod.id; tdName.textContent = prod.name; tdPrice.textContent = prod.price; }); });