Как мне отформатировать остальные API? - PullRequest
0 голосов
/ 17 апреля 2019

У меня на локальном хосте работает очень простой API RESTful, и он выглядит примерно так:

http://prntscr.com/nd8kpn

или в тексте:

{"course_id":"1",
"course_creator_id":"1",
"course_name":"Chanel Introduction",
"course_description":"In this course i will discuss info about myself and what you will be learning on my Chanel.",
"course_thumbnail":"\/public\/course_images\/0.jpg",
"date_added":"2019-04-17 15:25:39"
}
{"course_id":"2",
"course_creator_id":"1",
"course_name":"Getting started with Web Develop",
"course_description":"In this course, you will learn the basic concepts of Web Development. ",
"course_thumbnail":"\/public\/course_images\/1.jpg",
"date_added":"2019-04-17 15:25:39"
}
{"course_id":"3",
"course_creator_id":"1",
"course_name":"HTML and CSS Introduction",
"course_description":"In this course, I will go in depth on HTML, CSS and front end development of basic static webpages.",
"course_thumbnail":"\/public\/course_images\/2.jpg",
"date_added":"2019-04-17 15:25:39"
}
{"course_id":"4","course_creator_id":"1","course_name":"JavaScript and React Basics.","course_description":"In this course, we will dive deep into JavaScript and briefly go over the basics of React","course_thumbnail":"\/public\/course_images\/3.jpg","date_added":"2019-04-17 15:25:39"}
{"course_id":"5","course_creator_id":"1","course_name":"Building REST apis with Node and Express","course_description":"In this course, we will go in depth on REST apis and build one in the second half of the course.","course_thumbnail":"\/public\/course_images\/4.jpg","date_added":"2019-04-17 15:25:39"}
{"course_id":"6","course_creator_id":"1","course_name":"Building an e-books website from scratch","course_description":"In this course we will build an e-books website and combine everything from the previus 5 tutorials.","course_thumbnail":"\/public\/course_images\/5.jpg","date_added":"2019-04-17 15:25:39"}
{"course_id":"7","course_creator_id":"3","course_name":"What is Game Development","course_description":"In-depth look on game development (theory only, no code).","course_thumbnail":"\/public\/course_images\/6.jpg","date_added":"2019-04-17 15:25:39"}
{"course_id":"8","course_creator_id":"3","course_name":"C++ For Game Development","course_description":"In this massive course, i will teach you everything about C++ and touch on concepts for game development in C++.","course_thumbnail":"\/public\/course_images\/7.jpg","date_added":"2019-04-17 15:25:39"}
{"course_id":"9","course_creator_id":"3","course_name":"Introduction to Unreal Engine 4 ","course_description":"Here we will combine what you learnt in the previus course with Unreal Engine4 and start developing small games","course_thumbnail":"\/public\/course_images\/8.jpg","date_added":"2019-04-17 15:25:39"}
{"course_id":"10","course_creator_id":"3","course_name":"Making a turn based RPG with UE4 and C++","course_description":"In this tutorial, we will combined the previus 2 courses and make a turn based RPG from scratch","course_thumbnail":"\/public\/course_images\/9.jpg","date_added":"2019-04-17 15:25:39"}

Мой код выглядит следующим образом:

include('../connect.php');
$stmt = $db->query('SELECT * FROM courses');
$result = $stmt->fetchAll(PDO::FETCH_OBJ);

foreach($result as $row){

    if(isset($_GET['course_id'])){
        if($row->course_id == $_GET['course_id']){
            echo json_encode($row);
        }
    } else if (isset($_GET['creator_id'])){
        if($row->course_creator_id == $_GET['creator_id']){
            echo json_encode($row);
        }
    } else {
        echo json_encode($row);
    }

}

Как я уже сказал, очень просто. Я использую его как тестовый API, а не как производственный.

Мой вопрос: почему большинство REST API так хороши, как граф Facebook, но мои остальные API всегда имеют ужасный формат? Как мне сделать мой REST API красивым? : D

1 Ответ

4 голосов
/ 17 апреля 2019

Прежде всего вам нужно создать действительный вывод json, затем вам нужно объявить, что ваш вывод похож на json:

header('Content-Type: application/json');
include('../connect.php');
$stmt = $db->query('SELECT * FROM courses');
$result = $stmt->fetchAll(PDO::FETCH_OBJ);
$rows = [];
foreach($result as $row){
    if(isset($_GET['course_id'])){
        if($row->course_id == $_GET['course_id']){
            $rows[] = $row;
        }
    } else if (isset($_GET['creator_id'])){
        if($row->course_creator_id == $_GET['creator_id']){
             $rows[] = $row;
        }
    } else {
         $rows[] = $row;
    }
}
echo json_encode($rows, JSON_PRETTY_PRINT); 

JSON_PRETTY_PRINT отвечает за печать данных в строках, а не в одномлиния

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...