Dingo API - How to add version number in url?

主宰稳场 提交于 2020-05-29 08:45:17

问题


I have just installed Dingo and it appear to work with the following URL:

http://website.dev/api/test

http://website.dev/api/hello

$api = app('Dingo\Api\Routing\Router');
    $api->version('v1', function ($api) {

        $api->get('test', function () {
            return 'Test';
        });

        $api->get('hello', function () {
            return 'Hello';
        });

    });

I would like version v1 to be included in the URL, how do I get this to work? When I try:

http://website.dev/api/v1/test

I get error:

{
"message": "404 Not Found",
"status_code": 404
}

In the .env file, I have: API_PREFIX=api

According to Dingo Configuration:

Avoid putting a version number as your prefix or subdomain as versioning is handled via the Accept header.


回答1:


The version of dingoAPI don't work this way. Because they aren't versioning the API in the URI, you need to define an Accept header to request a specific version. The header is formatted like so:

Accept: application/vnd.YOUR_SUBTYPE.v1+json

For accessing the version you will need a HTTP Client like postman




回答2:


To work around the dingo version scheme, you could use route groups inside the version method and ignore the accept header. Something like this:

<?php

use Illuminate\Http\Request;

$api = app('Dingo\Api\Routing\Router');


$api->version('v1', function ($api) { // Always keep this to v1, and ignore accept header.

    $api->group(['prefix' => 'v1'], function ($api) { // Use this route group for v1

        $api->get('/', function () {
            return 'Look v1!';
        });

    });


    $api->group(['prefix' => 'v2'], function ($api) { // Use this route group for v2

        $api->get('/', function () {
            return 'Look v2!' ;
        });

    });

});


来源:https://stackoverflow.com/questions/38664222/dingo-api-how-to-add-version-number-in-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!