Sylius:全新安装但 API 不起作用

Sylius : Fresh install but API does not work

我是 Sylius 的初学者,我正在尝试使用 API,但它不起作用。每个结果都是“404 页面未找到”。

步骤:

一切正常,但是当我尝试使用 API 创建用户时,响应是“找不到路由(404 未找到)”HTML 页面。 (这是来自官方文档的第一个 API 调用:Sylius API doc

那是我的 OS 详细信息:

Distributor ID: Ubuntu
Description:    Ubuntu 21.04
Release:    21.04
Codename:   hirsute

我正在使用 Apache2 和 MySQL :

Server version: Apache/2.4.46 (Ubuntu)
Server built:   2021-09-28T10:57:42

mysql  Ver 8.0.27-0ubuntu0.21.04.1 for Linux on x86_64 ((Ubuntu))

当我使用命令时:

php bin/console debug:router api

我可以看到 189 个结果,我尝试了一些,例如:

+--------------+---------------------------------------------------------+
| Property     | Value                                                   |
+--------------+---------------------------------------------------------+
| Route Name   | api_doc                                                 |
| Path         | /api/v2/docs.{_format}                                  |
| Path Regex   | {^/api/v2/docs(?:\.(?P<_format>[^/]++))?$}sD            |
| Host         | ANY                                                     |
| Host Regex   |                                                         |
| Scheme       | ANY                                                     |
| Method       | ANY                                                     |
| Requirements | NO CUSTOM                                               |
| Class        | Symfony\Component\Routing\Route                         |
| Defaults     | _api_respond: true                                      |
|              | _controller: api_platform.action.documentation()        |
|              | _format:                                                |
| Options      | compiler_class: Symfony\Component\Routing\RouteCompiler |
+--------------+---------------------------------------------------------+

URL : http://myproject.local/api/v2/docs 但结果是一样的

我是不是漏掉了什么?

嗯,我忘了激活 API :

如文档所述,“新的统一 Sylius API 仍在开发中”因此需要启用此功能。

编辑 config/packages/_sylius.yaml 添加:

sylius_api:
    enabled: true

现在API被激活,路由不再响应404。

最后一件事,在您实际使用 API 之前,您需要生成一个 JWT 密钥对,否则 API 调用将 return “无法创建从给定配置签署 JWT".

为此,请使用 JWT 包 (Lexik Repository) :

php bin/console lexik:jwt:generate-keypair

现在一切都很好,您可以使用 API,享受 :)