Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

¡Instalación de la plataforma API!

Video not working?

It looks like your browser may not support the H264 codec. If you're using Linux, try a different browser or try installing the gstreamer0.10-ffmpeg gstreamer0.10-plugins-good packages.

Thanks! This saves us from needing to use Flash or encode videos in multiple formats. And that let's us get back to making more videos :). But as always, please feel free to message us.

¡Hola amigos! Es hora de hablar de... redoble de tambores... cómo hacer un delicioso pastel que parece una Oreo. Espera... ¡ah! Tutorial equivocado. Es hora de hablar de la Plataforma API... tan divertida que es casi tan deliciosa como un pastel con forma de Oreo.

La Plataforma API está arrasando estos días. Tengo la impresión de que en todas partes alguien habla maravillas de ella Su desarrollador principal, Kévin Dunglas, es un colaborador principal de Symfony, un tipo muy agradable y está ampliando absolutamente los límites de lo que pueden hacer las API. Vamos a verlo de primera mano. Además, ¡ha tenido la amabilidad de guiarnos en este tutorial!

Las API modernas son difíciles. La Plataforma API no lo es

Si sólo necesitas construir unas pocas rutas de API para soportar algo de JavaScript, puede que pienses:

¿Cuál es el problema? ¡Devolver algo de JSON aquí y allá ya es bastante fácil!

Yo he tenido esta misma opinión durante un tiempo. Pero poco a poco, creo que esto es cada vez menos cierto. Al igual que nacieron los frameworks cuando las aplicaciones web se volvieron más y más complejas, se han creado herramientas como API Platform porque lo mismo está ocurriendo actualmente con las API.

Hoy en día, las API son algo más que devolver JSON: se trata de ser capaz de serializar y deserializar tus modelos de forma coherente, quizá en múltiples formatos, como JSON o XML, pero también JSON-LD o HAL JSON. Luego están los hipermedios, los datos enlazados, los códigos de estado, los formatos de error, la documentación -incluida la documentación de las especificaciones de la API que puede alimentar a Swagger-. Luego está la seguridad, el CORS, el control de acceso y otras características importantes como la paginación, el filtrado, la validación, la negociación del tipo de contenido, el GraphQL... y... sinceramente, podría seguir.

Por eso existe la Plataforma API: para permitirnos construir APIs increíbles y amar el proceso ¿Y esa gran lista de cosas que acabo de mencionar que necesita una API? La Plataforma API viene con todo ello. Y no es sólo para construir una enorme API, sino que es la herramienta perfecta, incluso si sólo necesitas unas pocas rutas para potenciar tu propio JavaScript.

Distribución de la Plataforma API

¡Así que vamos a hacerlo! La Plataforma API es una biblioteca PHP independiente que está construida sobre los componentes de Symfony. No es necesario que la utilices desde dentro de una aplicación Symfony, pero, como puedes ver aquí, así es como recomiendan utilizarla, lo cual es genial para nosotros.

Si sigues su documentación, tienen su propia distribución de la Plataforma API: una estructura de directorios personalizada con un montón de cosas: un directorio para tu API impulsada por Symfony, otro para tu frontend de JavaScript, otro para un frontend de administración, ¡todo conectado con Docker! ¡Vaya! Puede parecer un poco "grande" para empezar, pero obtienes todas las características fuera de la caja... incluso más de lo que acabo de describir. Si eso suena increíble, puedes utilizarlo totalmente.

Pero vamos a hacer algo diferente: vamos a instalar la Plataforma API como un paquete en una aplicación Symfony normal y tradicional. Esto hace que el aprendizaje de la Plataforma API sea un poco más fácil. Una vez que te sientas seguro, para tu proyecto, puedes hacerlo de esta misma manera o lanzarte a utilizar la distribución oficial. Como he dicho, es súper potente.

Configuración del proyecto

De todos modos, para convertirte en el héroe de la API que todos necesitamos, deberías codificar conmigo descargando el código del curso desde esta página. Después de descomprimirlo, encontrarás un directorio start/ dentro con el mismo código que ves aquí... que en realidad es sólo un nuevo proyecto esqueleto de Symfony 4.2: no hay nada especial instalado ni configurado todavía. Sigue el archivo README.md para las instrucciones de configuración.

El último paso será abrir un terminal, entrar en el proyecto e iniciar el servidor Symfony con:

symfony serve -d

Esto utiliza el ejecutable symfony - una pequeña e impresionante herramienta de desarrollo que puedes obtener en https://symfony.com/download. Esto inicia un servidor web en el puerto 8000 que se ejecuta en segundo plano. Lo que significa que podemos encontrar nuestro navegador, dirigirnos alocalhost:8000 y ver... bueno, ¡básicamente nada! Sólo la bonita página de bienvenida que se ve en una aplicación Symfony vacía.

Instalar la plataforma API

Ahora que tenemos nuestra aplicación Symfony vacía, ¿cómo podemos instalar la Plataforma API? Es increíble. Busca tu terminal y ejecuta:

composer require api:1.2.0

Eso es. Te darás cuenta de que esto está instalando algo llamadoapi-platform/api-pack. Si recuerdas nuestra serie sobre Symfony, un "paquete" es una especie de biblioteca "falsa" que ayuda a instalar varias cosas a la vez.

Por ejemplo, puedes ver esto en https://github.com/api-platform/api-pack: es un único archivocomposer.json que requiere varias bibliotecas, como Doctrine, un paquete CORS del que hablaremos más adelante, anotaciones, la propia Plataforma API y algunas partes de Symfony, como el sistema de validación, el componente de seguridad e incluso Twig, que se utiliza para generar una documentación realmente interesante que veremos en un minuto.

Pero aún no hay nada tan interesante: sólo la Plataforma API y algunos paquetes estándar de Symfony.

De vuelta al terminal, ¡ya está hecho! Y tiene algunos detalles sobre cómo empezar. También se han ejecutado algunas recetas que nos han proporcionado algunos archivos de configuración. Antes de hacer nada más, vuelve al navegador y dirígete ahttps://localhost:8000/api para ver... ¡woh! ¡Tenemos la documentación de la API! Bueno, todavía no tenemos ninguna API... así que aquí no hay nada. Pero ésta va a ser una característica enorme y gratuita que obtendrás con la Plataforma API: a medida que construyamos nuestra API, esta página se actualizará automáticamente.

Veamos eso a continuación creando y exponiendo nuestro primer Recurso API.

Leave a comment!

114
Login or Register to join the conversation
Ajie62 Avatar

Hey, thank you for this course. I think API Platform is great! I've been learning it for days now and I can't wait to see what you're going to teach us here. Keep up the good work, that's fantastic!

4 Reply

Thanks Ajie62 :)

Reply

Hi there!

Just started tutorial and got an error while installing the project.

Cache clear fail :-(

!! PHP Fatal error: Could not check compatibility between Symfony\Bridge\ProxyManager\LazyProxy\PhpDumper\LazyLoadingValueHolderGenerator::generate(ReflectionClass $originalClass, Zend\Code\Generator\ClassGenerator $classGenerator) and ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator::generate(ReflectionClass $originalClass, Laminas\Code\Generator\ClassGenerator $classGenerator), because class Zend\Code\Generator\ClassGenerator is not available in /home/atournayre/PhpstormProjects/code-api-platform/start/vendor/symfony/proxy-manager-bridge/LazyProxy/PhpDumper/LazyLoadingValueHolderGenerator.php on line 33
!!
!! In LazyLoadingValueHolderGenerator.php line 33:
!!
!! Compile Error: Could not check compatibility between Symfony\Bridge\ProxyMa
!! nager\LazyProxy\PhpDumper\LazyLoadingValueHolderGenerator::generate(Reflect
!! ionClass $originalClass, Zend\Code\Generator\ClassGenerator $classGenerator
!! ) and ProxyManager\ProxyGenerator\LazyLoadingValueHolderGenerator::generate
!! (ReflectionClass $originalClass, Laminas\Code\Generator\ClassGenerator $cla
!! ssGenerator), because class Zend\Code\Generator\ClassGenerator is not avail
!! able

More about this error here : https://github.com/atournay...

I didn't manage to find a solution to this problem.

Anyone can help me solving this ?

Thanks!

2 Reply

I manage to make it work using : composer require api-platform/api-pack "1.2.0"

Thanks to finish folder in the course code.
Dependencies update is a very big problem in tutorials! (already talked about that with Ryan)

2 Reply

Hey atournayre!

This definitely sounds like a problem :). We have a new course "continuous integration" system (we just finished v1 2 days ago) - it sounds like we need to hook this course up to that and see what's going on.

Cheers!

2 Reply
Pierre Avatar

Hi Ryan, is this new course finished yet? Also, like Aurélien I stumbled upon lots of compatibility errors while doing this tutorial, which made me temporarily gave up, trying to gain more symfony experience elsewhere. But it would be nice if all those api-platforms tutorials would be ported to symfony 6. Any plans to do that? Thanks for the good work anyway.

Reply

Hey Pierre!

Yes, this course is finished. And, it should work just fine.... if you're using OUR code with our Symfony version. So, indeed, if you try to apply this to a Symfony 6 project, there will be some changes (not really much related to API Platform itself, but things more related to Symfony). We will upgrade these tutorials... but I'm not sure when. I need to check with the API Platform team to see what their roadmap is (so we don't upgrade these tutorials... only for them to release some big features right after!).

In the mean time, if you have some compat errors, we can definitely help debug those. Sorry I can't give a better answer!

1 Reply
Emanuele-P Avatar
Emanuele-P Avatar Emanuele-P | posted hace 1 mes

Hallo @weaverryan, we have develop an app in symfony 6.1 and apiplatform 2.6, we have been successfully moved to version 2.7.2 with the flag to be ready for 3
but when i try to go further ( with version 3 ) i find out the a lot of changes happen in the @context, i could not find any proper info about it ( not in the docs at least), is it possible to have more info about it?

Reply

Hey Emanuele-P!

we have been successfully moved to version 2.7.2 with the flag to be ready for 3

Nice!

but when i try to go further ( with version 3 ) i find out the a lot of changes happen in the @context, i could not find any proper info about it ( not in the docs at least), is it possible to have more info about it?

We're' going to make a tutorial for API Platform 3 before the year is over - it's one of my top priorities. I'll be sure to mention, in that tutorial, as many differences as I can before 2 and 3 to help ease the transition. So, it's coming!

Cheers!

Reply
Ninsky Avatar

Is it possible to disable SwaggerUI on production when env=prod in .env?

Reply

Hey Ninsky!

I believe you could do something like:

when@prod:
    api_platform:
        enable_swagger: false
        enable_swagger_ui: false

I believe the difference between those two options is that the UI prevents the HTML version of the page being loaded, but enable_swagger controls if you could see the JSON version of the "open api" docs.

Let me know if that helps :).

Cheers!

Reply
Ninsky Avatar

Hello Ryan

Thanks for your help! Will give it a try. Also found the following params which I will test:

when@prod:
  api_platform:
    enable_docs: false
    enable_entrypoint: false

Have a nice day
Ninsky

Reply

Hello! Many thanks for this tutorial!

My API bundle works perfectly between my Angular frontend part and my Symfony backend part without doing Auth to my app. After adding the auth configration to my symfony app I can't post the data from angular anymore. Here is the message that i found in the inspecter:

Access to XMLHttpRequest at 'https://localhost:8000/api/link' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am also using NelmioCorsBundle to avoid this problem but it doesn't work:


nelmio_cors:
defaults:
allow_credentials: false
allow_origin: []
allow_headers: []
allow_methods: []
expose_headers: []
max_age: 0
hosts: []
origin_regex: false
forced_allow_origin_value: ~

paths:
'^/api/':
allow_origin: ['*']
allow_headers: ['X-Custom-Auth']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
max_age: 3600

'^/':
origin_regex: true
allow_origin: ['^http://localhost:[0-9]+']
allow_headers: ['X-Custom-Auth']
allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
max_age: 3600
hosts: ['^api\.']

I also disable the security in Chrome and get this error
ERR_CERT_AUTHORITY_INVALID

Many thansk for your help!! Really appreciate your support :)

Reply

Hey Lubna

It seems like you're doing the request to a non https endpoint. Try updating your Nelmio config - change the allow_origin key to allow HTTPS

Cheers!

Reply
Benoit-L Avatar
Benoit-L Avatar Benoit-L | posted hace 8 meses

Hi there, I have uploaded the directory start and run the following : symfony serve -d but I have got the following error message : Cette page n’est pas disponible pour le moment127.0.0.1 ne peut actuellement pas traiter cette demande.
HTTP ERROR 500.

I have solved the problem doing an composer update.

Reply

Hey Benoit L.!

Thanks for sharing your solution :). I'm not sure what happened, but the course does require a composer update if you're using PHP 8. We don't update the course download code because we want it to match what you see in the video exactly.

Cheers!

Reply
Benoit-L Avatar

In fact, I'm facing this problem again this morning. And my version of PHP is 7.4.13.
I have created the bookshop-api proposed on the https://api-platform.com/do... and when I run the same command it works with the command symfony serve -d. So the only 2 differences I see is that when I have created the project following the instructions of api-Platform we start by running the instructions "composer create-project symfony/skeleton bookshop-api " and after that we run the instruction "composer require api". I could try to create the start project with those instructions then importing the files inside the project.
What do you think ?

Reply

Hey @Benoit!

Apologies for the slow reply! Ok, let's see:

> Is is normal that there is this file htaccess with "Deny from all"

What htaccess file are you referring to? I don't see any htaccess file when I download the course code from this page, and I wouldn't expect to see any .htaccess files. Do you see one somewhere?

> could try to create the start project with those instructions then importing the files inside the project.

You could certainly try that! Though, I *would* love to figure out the underlying problem that you're having :).

Cheers!

Reply
Benoit-L Avatar

I'm creating the project inside Php Storme and I see this file. I would like to add a screen shot but I am not sure how to do it.
This is the message that I get when I run symfony server:start : [Web Server ] Mar 26 20:32:57 |ERROR | SERVER GET (500) / ip="127.0.0.1".
I see this message in the log as well : [Web Server ] [26-Mar-2022 19:32:57 UTC] PHP Fatal error: require(): Failed opening required 'C:\wamp64\www\api-platform\start/vendor/autoload.php'
And when I run the same command on the finish project I have the same error which seems to me weird.

Reply
Benoit-L Avatar

concerning the .htaccess file it is in the cache folder both in the start and the finish projects. I don't have the image icon to share with you the screenshot otherwise you would have no choice than to believe me :)

-1 Reply

Hey Benoit L.!

Sorry for the slow reply!

> [Web Server ] [26-Mar-2022 19:32:57 UTC] PHP Fatal error: require(): Failed opening required 'C:\wamp64\www\api-platform\start/vendor/autoload.php'

Hmm. This looks like you should run composer install. Did you run that? There is a README.md file in each directory (start or finish) with the commands you'll need to get everything up and running.

> concerning the .htaccess file it is in the cache folder both in the start and the finish projects

Ah, the cache/ folder - var/cache right? Interesting. When I download the course code from this page, there is NO var/ directory at all (which is correct: this file is created on demand by Symfony whenever it's needed). But, it doesn't really matter: the cache directory isn't meant to be publicly accessible anyways, so an .htaccess in that directory wouldn't cause any problems :).

Cheers!

Reply
Benoit-L Avatar

Yes, sorry for this. I've got a new error now when I run:

$ php bin/console doctrine:migrations:migrate

Attempted to call an undefined method named "getAllRawData" of class "Composer\InstalledVersions"

Reply

Hey Benoit L.!

Sorry for the slow reply! Hmm. Try upgrading Composer. I'm seeing that this getAllRawData() method, which lives in Composer, was introduced in version 2.0.14. That's my first guess: it's a very odd error :/.

Cheers!

1 Reply
davidmintz Avatar
davidmintz Avatar davidmintz | posted hace 10 meses

My machine has php8.1 installed and composer install doesn't like it. I tried hacking the PHP version string in composer.json like so:

"php": "^7.1.3 || 8.*",

and then I tried composer update with the result


Your requirements could not be resolved to an installable set of packages.


Problem 1
- symfony/console[v4.2.0, ..., v4.2.12] require php ^7.1.3 -> your php version (8.1.1) does not satisfy that requirement.
- Root composer.json requires symfony/console 4.2.* -> satisfiable by symfony/console[v4.2.0, ..., v4.2.12].

What solution would you recommend? Thanks.

Reply

Hey Elliott,

We're sorry about that. Unfortunately, this course isn't compatible with PHP 8 out of the box, and we warn about it with a tooltip when you download the course code. We do recommend to run the course project code on PHP 7.x to be able execute "composer install" command successfully. But if you do want to run it on PHP 8 - you would need to update the dependencies that may lead to more required steps to make the project code to work on PHP 8.

The change you made in the composer.json is the first step. But looks like this course is based on Symfony 4.2, and the latest version 4.2.12 does not support PHP 8 either, see: https://github.com/symfony/...

So, to be able to run this project on PHP 8 - you will need to upgrade Symfony to 4.4 at least first, that may require more work. If you want - you can go this way, or fallback to PHP 7.x.

I hope this helps!

Cheers!

Reply
Serkan Avatar

Hi;
I want to use docker database in this tutorial. I created a docker-compose file by maker command. But while creating entity for CheeseListing I got an error like Invalid argument supplied for foreach(). I couldn't crate an entity.

Reply

Hey Serkan,

It's difficult to tell you what's wrong exactly. Please, try to debug things yourself. Error message will give you some hints about what file, what line. Open that file and try to debug the argument that is supplied to that foreach - you can use "dd($variableName)" to dump the variable. Then, try to debug why you're passing there not an array and where. Then, it should be easy to fix.

I hope this helps!

Cheers!

Reply
Covi A. Avatar
Covi A. Avatar Covi A. | posted hace 1 año

thanks for your answer, i solved it.

Reply
Covi A. Avatar
Covi A. Avatar Covi A. | posted hace 1 año

Hi
i am trying to install doctrine for work with docker but when i install orm (composer require orm) then orm install successfully but command prompt not work correctly. and for this reason i could not create database.
when i am try this command php bin/console then it's show me this error

An option named "connection" already exists.

can you help me about this problem

Reply

Hey Covi A.

If you're using Docker, first double-check that your MySql instance it's up and running, then, you'll have to run symfony commands through the Symfony CLI symfony console doctrine:database:create, so it can automatically inject the right environment variables, for example, the database URL coming from your Docker instance
Here you can download the Symfony CLI https://symfony.com/download

Cheers!

Reply
Dennis B. Avatar
Dennis B. Avatar Dennis B. | posted hace 1 año

I've set up the project using Symfony 5.2.5 and API Platform 2.6.3.
When I try to access "http://localhost:8000/api" I am presented an Exception telling me "Unable to generate a URL for the named route "api_doc" as such route does not exist."
Is there anything I can do to get the thing to work?

Thanks in advance.

Reply

Hey Dennis B.

Did you notice if a "recipe" was installed when you installed ApiPlatform? You should have gotten this file config/routes/api_platform.yaml
Cheers!

Reply
Dennis B. Avatar
Dennis B. Avatar Dennis B. | MolloKhan | posted hace 1 año | edited

Hi MolloKhan !

Yes, that file I have. And it contains:
api_platform:
mapping:
paths: ['%kernel.project_dir%/src/Entity']
patch_formats:
json: ['application/merge-patch+json']
swagger:
versions: [3]

Reply

I believe you checked the wrong file. I'm talking about the file inside config/routes. Its content should be like this one https://github.com/symfony/...

Cheers!

Reply
Dennis B. Avatar

Ah, okay. Sorry.
Also this file I have and it looks exactly like the one on github, you did link.

Reply

Hmm, that's really weird. What's the output of `bin/console debug:router`? For some reason it's not loading the ApiPlatform route

Reply
Dennis B. Avatar

The output doesn't show any route.
➜ api-platform git:(master) ✗ bin/console debug:router
------ -------- -------- ------ ------
Name Method Scheme Host Path
------ -------- -------- ------ ------

➜ api-platform git:(master) ✗

"api-platform" is also the folder's name of my project. But I cannot imagine that this would be a problem.

Reply
Dennis B. Avatar

Well, since I had not really a project so far, I decided to throw everything away and gave it a new try.

So, I copied the stuff from the tutorial's "start" directory, adjusted the packages' version numbers to 5.x, reinstalled the packages and now it works fine.

Reply

Hey Dennis B.

Sorry for my slow reply. I believe you had a configuration problem. Your routes weren't being loaded for some reason. I'm glad to hear that your project it's set up now. Let us know if you run into more troubles

Cheers!

Reply
Jakub R. Avatar

Hi guys, thanks for the great work. I am having the same problem, but I have a larger project that I cannot afford to rewrite. Any other ideas, why it is not loading the routes? I have tried a new project and it work with that. I have also for testing purposes removed my access_control rules (left only - { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY })

I am using in some cases groups and serializer and json response to make some rest endpoints. Can that collide?

Reply
Jakub R. Avatar

Nevermind. Composer install was the trick. It runs now. My bad :)

1 Reply
Miky Avatar

Sorry if you marked me fist as spam... too much text from console... but question is simple...
Why composer install wont run on php 8 version but only on 7.1.3+ version max to 7.4 version
What do i need to setup ?

From console i did 14 problems with similar context
Problem 1 ....

- Root composer.json requires php ^7.1.3 but your php version (8.0.2) does not satisfy that requirement.

Reply

Hey Miky!

It's an excellent question actually :). API Platform itself runs *fine* on PHP 8. But at the time we created *this* tutorial, PHP 8 wasn't released yet. And so, some of the dependencies in our composer.lock file do not support PHP 8. We try not to upgrade our course code in any significant way after it's released so that it stays "in sync" with the video. For that reason, our code doesn't work with PHP 8.

But, you are totally free to upgrade the packages if you'd like to get them working on PHP 8. You can run this command to see what needs to be upgraded:


composer why-not "php:^8.0"

Let me know if that helps!

Cheers!

1 Reply
Aleksander R. Avatar
Aleksander R. Avatar Aleksander R. | weaverryan | posted hace 1 año

Hello,
I have the same problem.

I followed your advice and run "composer why-not "php:^8.0".

I received this:
__root__ - requires php (^7.1.3)

What should I do next?

Reply

Hey @Aleksander!

Ah, excellent! This is the easiest one to solve (once you know what it means!). It means that in the composer.json in your app, you have a require.php key set to ^7.1.3. Change that to ^8.0.0. or ^7.1.3||^8.0.0 if you want, and you should be good. Doing a composer up afterwards will update dependencies to work with PHP 8. Oh, and also check to see if you have a config.platform.php setting. If you do, simply remove that or update that to whatever *actual* PHP version you're running on production. Here are some details on that setting https://getcomposer.org/doc...

Cheers!

Reply
Aleksander R. Avatar
Aleksander R. Avatar Aleksander R. | weaverryan | posted hace 1 año

My composer.json file now looks like this:


"require": {
"php": "^8.0.0",
"ext-ctype": "*",
"ext-iconv": "*",
"composer/package-versions-deprecated": "^1.11",
"symfony/console": "4.2.*",
"symfony/dotenv": "4.2.*",
"symfony/flex": "^1.1",
"symfony/framework-bundle": "4.2.*",
"symfony/yaml": "4.2.*"
},
"config": {
"preferred-install": {
"*": "dist"
},
"sort-packages": true
},

But when I run "composer up" I still get this problem:

Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
- symfony/console[v4.2.0, ..., v4.2.12] require php ^7.1.3 -> your php version (8.0.0) does not satisfy that requirement.
- Root composer.json requires symfony/console 4.2.* -> satisfiable by symfony/console[v4.2.0, ..., v4.2.12].

Reply

Hey @Aleksander!

Ah! I see. You are also going to need to upgrade Symfony to at least version 4.4 in your composer.json. I'm not sure why that didn't show up when you ran composer why-not "php:^8.0"... that's the purpose of that command.

Cheers!

Reply
Aleksander R. Avatar

I just created my new skeleton project and it seems that I can code along with your tutorials. Is there anything important in your starting code or I can just go on with my project?

P.S. Buying too much cheese every time I enter the store is the story of my life too ;)

Reply

Hey Aleksander!

Sorry for the slow reply - for some reason Disqus flagged your comment as "needing moderation" - it must have been all that talk about buying cheese! ;)

> Is there anything important in your starting code or I can just go on with my project?

The downloaded project *does* have a lot of code in it, like the CheeseListing entity, etc. But, overall, there is nothing *too* special about it (but I don't know for sure how we've customized it - though we try to keep pre-tutorial customizations very small to keep things realistic). If you hit any surprises along the way, let us know and we can help point you in the right direction :).

Cheers!

Reply
Wolfone Avatar
Wolfone Avatar Wolfone | posted hace 1 año

Hi there!

First thing: awesome courses!

Second thing -> a question: I included ApiPlatform into an existing project (composer require api) and declared one of my entities to be an @ApiResource.

Context: Symfony 5.2

Using a local dev-server (symfony server:serve).

Weirdly https://localhost:8000/api returns a slightly disfunctional version of my app's landing-page.

I thought that maybe some existing routes that have https://localhost:8000/api as a prefix might mess with the internals so i searched for those and temporarily changed them to something else. To no effect.

Furthermore navigating to "https://localhost:8000/api/corporate_bodies" shows the corresponding doc-page just fine.

Any idea why this might happen/how to fix this?

Reply
Cat in space

"Houston: no signs of life"
Start the conversation!

Este tutorial funciona muy bien para Symfony 5 y la Plataforma API 2.5/2.6.

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": "^7.1.3",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "api-platform/core": "^2.1", // v2.4.3
        "composer/package-versions-deprecated": "^1.11", // 1.11.99
        "doctrine/annotations": "^1.0", // 1.10.2
        "doctrine/doctrine-bundle": "^1.6", // 1.11.2
        "doctrine/doctrine-migrations-bundle": "^2.0", // v2.0.0
        "doctrine/orm": "^2.4.5", // v2.7.2
        "nelmio/cors-bundle": "^1.5", // 1.5.5
        "nesbot/carbon": "^2.17", // 2.19.2
        "phpdocumentor/reflection-docblock": "^3.0 || ^4.0", // 4.3.1
        "symfony/asset": "4.2.*|4.3.*|4.4.*", // v4.3.11
        "symfony/console": "4.2.*", // v4.2.12
        "symfony/dotenv": "4.2.*", // v4.2.12
        "symfony/expression-language": "4.2.*|4.3.*|4.4.*", // v4.3.11
        "symfony/flex": "^1.1", // v1.17.6
        "symfony/framework-bundle": "4.2.*", // v4.2.12
        "symfony/security-bundle": "4.2.*|4.3.*", // v4.3.3
        "symfony/twig-bundle": "4.2.*|4.3.*", // v4.2.12
        "symfony/validator": "4.2.*|4.3.*", // v4.3.11
        "symfony/yaml": "4.2.*" // v4.2.12
    },
    "require-dev": {
        "symfony/maker-bundle": "^1.11", // v1.11.6
        "symfony/stopwatch": "4.2.*|4.3.*", // v4.2.9
        "symfony/web-profiler-bundle": "4.2.*|4.3.*" // v4.2.9
    }
}