在 laravel5.4 中创建 REST API

Create RESTAPI in laravel5.4

我正在尝试在 laravel5.4 中创建一个 RESTAPI。所以我写了所有的代码。我在 api.php 中定义了我的路由文件。当我在邮递员中 运行 时,它不起作用。然后我在 web.php 中更改了我的路由文件。然后我 运行 再次在邮递员中。然后它的工作。为什么它在 api.php 文件中不起作用?

我们必须在 api.phpweb.php 文件中定义我们的 roue 文件?

请帮助我。我只是很困惑。

这是我的 roue 文件示例:(api.php)

Route::get('sample-restful-apis', function()
{
    return array(
      1 => "expertphp",
      2 => "demo"
    );
});

请尝试在 url 中使用 /api,因为 api url 自动具有 api 前缀。 在你的例子中 /api/sample-restful-apis.

您在web.php中定义路由文件。

此路由在 web.php 文件中用数组文件定义并在浏览器中直接 sample-restful-apis 键入得到响应

Route::get('sample-restful-apis', function()
{
    return array(
      1 => "expertphp",
      2 => "demo"
    );
});
  1. 在 routes/api.php 中,为 apis.
  2. 创建所有路由
  3. 在 app/Http/Controllers/Api 中创建名为 v1 的文件夹。把你需要的控制器放进去。
  4. 例如,您想要获取 id 类型值,然后首先为其创建路由。

    Route::get('/getidtype', 'Api\V1\UsersController@getIdtype');这样。

  5. 创建或使用创建的控制器,如 UsersController.php。为 return 这样的响应创建函数

    public function getIdtype(Request $request){
            $idtypes = IdType::get();
            if(sizeOf($idtypes) > 0){
                echo "ID Types:";
                return $idtypes;
            }else{
                echo "No IdType Exist";
    

    } }

  6. 在 api 工具或网址如 http://localhost:8000/api/getidtype

  7. 调用此函数

你会得到你想要的回应。继续享受。