Flag of Ukraine
SymfonyCasts stands united with the people of Ukraine

Instalación de la API Platform

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 y bienvenidas, hermosas personas, a un tutorial que me es muy querido: cómo construir magníficos castillos con Legos. Sería increíble, ¿verdad? Pero en realidad, estamos aquí para hablar de la API Platform Versión 3, que prometo que es tan divertida como jugar con Legos. Pero no le digas a mi hijo que he dicho eso.

La API Platform es, sencillamente, una herramienta sobre Symfony que nos permite crear API potentes y disfrutar del proceso Existe desde hace años y, sinceramente, lo está petando. Tienen su propia conferencia dedicada y, realmente, se han superado a sí mismos con la última versión 3.

Si eres nuevo en la API Platform, no te culparía si dijeras:

Vamos Ryan... crear una API no es tan difícil. Sólo se trata de devolver JSON: un ¡un montón de garabatos y corchetes!

Vale, eso es cierto (al menos para las primeras rutas). Pero hay un montón de pequeños detalles a los que prestar atención. Por ejemplo, si tienes una API que devuelve datos de productos, querrás que ese JSON del producto se devuelva de la misma manera, con los mismos campos, en todas las rutas. Ese proceso se llama serialización. Además, muchas API devuelven ahora campos adicionales que describen el significado de los datos. Vamos a ver y hablar de algo llamado "JSON-LD", que hace exactamente eso.

¿Qué más? ¿Qué hay de la documentación? Idealmente, documentación interactiva que se genere automáticamente... porque no queremos construir y mantener eso a mano. Incluso si estás construyendo una API sólo para ti, tener documentación es genial. Paginar colecciones también es superimportante, filtrar y buscar colecciones, validación y negociación del tipo de contenido, que es cuando ese mismo producto podría devolverse como JSON, CSV u otro formato. Así que sí, crear una ruta API es fácil. Pero crear una API rica es algo totalmente distinto. Y ése es el objetivo de la API Platform. Ah, y si estás familiarizado con la versión 2 de la API Platform, la versión 3 te resultará muy familiar. Simplemente es más limpia, más moderna y más potente. Así que saca tus Legos, ¡y hagámoslo!

La distribución de la API Platform

Hay dos formas de instalar la API Platform. Si encuentras su sitio web y haces clic en la documentación, verás que hablan de la "Distribución" de la API Platform. ¡Esto está muy bien! Es un proyecto completamente prefabricado con Docker que te ofrece un lugar para construir tu API con Symfony, un área de administración React, andamiaje para crear un frontend Next.js y mucho más. Incluso te proporciona un servidor web listo para producción con herramientas adicionales como Mercure para actualizaciones en tiempo real. Es la forma más potente de utilizar la API Platform.

Pero... en este tutorial, no vamos a utilizarla. ¡Odio las cosas bonitas! No, empezaremos nuestro proyecto Lego desde cero: con una aplicación Symfony perfectamente normal y aburrida. ¿Por qué? Porque quiero que veas exactamente cómo funciona todo bajo el capó. Luego, si quieres utilizar esta Distribución más adelante, puedes hacerlo.

Configuración del proyecto y nuestro proyecto

Bien, para ser un verdadero "Campeón de la Devolución JSON de la API Platform", ¡deberías codificar conmigo! Descarga el código fuente de esta página. Y tras descomprimirlo, encontrarás un directorio start/ con el mismo código que ves aquí. Se trata de un nuevo proyecto Symfony 6.2 con... absolutamente nada en él. Abre este archivoREADME.md para ver todas las instrucciones de configuración. El último paso será abrir el proyecto en un terminal y utilizar el binario de Symfony para ejecutarlo:

symfony serve -d

Esto inicia un servidor web local en 127.0.0.1:8000. Haré trampas y haré clic en ese enlace para abrir... un proyecto Symfony 6.2 completamente vacío. Aquí no hay literalmente nada, excepto esta página de demostración.

¿Qué vamos a construir? Como todos sabemos, a Internet le falta algo terriblemente importante: ¡una aplicación para que los dragones presuman de sus tesoros robados! Porque si hay algo que le gusta más a un dragón que un tesoro, es presumir de él. Sí, crearemos una rica API que permita a los dragones expertos en tecnología publicar nuevos tesoros, buscar tesoros, buscar tesoros de otros dragones, etc. Y sí, acabo de terminar de leer El Hobbit.

Instalación de la API Platform

Vamos a instalar la API Platform Vuelve a tu terminal y ejecuta:

composer require api

Este es un alias de Symfony Flex. Aquí arriba, puedes ver que en realidad está instalando algo llamado api-platform/api-pack. Si no estás familiarizado, un "paquete" en Symfony es una especie de paquete falso, que te permite instalar fácilmente un conjunto de paquetes. Si te desplazas hacia abajo, instaló el propio api-platform, Doctrine, puesto que aún no lo tenía, y algunos otros paquetes. Al final... veamos... la recetadoctrine-bundle nos pregunta si queremos incluir un archivo docker-compose.ymlpara ayudarnos a añadir una base de datos a nuestro proyecto. ¡Qué bien! Esto es opcional, pero voy a decir "p" por "Sí permanentemente". Y... ¡listo!

Lo primero que hay que ver es el archivo composer.json:

85 lines composer.json
{
... lines 2 - 5
"require": {
"php": ">=8.1",
"ext-ctype": "*",
"ext-iconv": "*",
"api-platform/core": "^3.0",
"doctrine/annotations": "^1.0",
"doctrine/doctrine-bundle": "^2.8",
"doctrine/doctrine-migrations-bundle": "^3.2",
"doctrine/orm": "^2.14",
"nelmio/cors-bundle": "^2.2",
"phpdocumentor/reflection-docblock": "^5.3",
"phpstan/phpdoc-parser": "^1.15",
"symfony/asset": "6.2.*",
"symfony/console": "6.2.*",
"symfony/dotenv": "6.2.*",
"symfony/expression-language": "6.2.*",
"symfony/flex": "^2",
"symfony/framework-bundle": "6.2.*",
"symfony/property-access": "6.2.*",
"symfony/property-info": "6.2.*",
"symfony/runtime": "6.2.*",
"symfony/security-bundle": "6.2.*",
"symfony/serializer": "6.2.*",
"symfony/twig-bundle": "6.2.*",
"symfony/validator": "6.2.*",
"symfony/yaml": "6.2.*"
},
... lines 33 - 83
}

Como prometí, ese paquete API Platform añadió un montón de paquetes a nuestro proyecto. Técnicamente, no todos son necesarios, pero esto nos va a dar una experiencia realmente rica construyendo nuestra API. Y si ejecutas

git status

... ¡sí! Ha actualizado los archivos habituales... y también ha añadido un montón de archivos de configuración para los nuevos paquetes. Parece que hay mucho... pero las apariencias engañan. Todos estos directorios están vacíos... y los archivos de configuración son pequeños y sencillos. También tenemos algunos archivos docker-compose que utilizaremos en un minuto para poner en marcha una base de datos.

Así que... ahora que la API Platform está instalada... ¿ya nos ha dado algo? Sí, y es genial Vuelve al navegador y dirígete a /api. ¡Vaya! ¡Tenemos una página de documentación de la API! Está vacía porque, ya sabes, todavía no tenemos una API, pero pronto cobrará vida.

A continuación: Vamos a crear nuestra primera entidad Doctrine y a "exponerla" como Recurso API. Es hora de hacer algo de magia.

Leave a comment!

24
Login or Register to join the conversation
Elijah Avatar

Can this project be run using Docker, and what are the specifics of such a deployment? Is there a recommended Dockerfile? I tried setting up the project with this Dockerfile, unfortunately, it didn't work: the container configured without errors but is not accessible at http://127.0.0.1:8000/.

FROM php:8.1-fpm 

RUN apt-get update && apt-get install -y \ 
    unzip \ 
    libzip-dev \ 
    curl \ 
  && docker-php-ext-configure zip \ 
  && docker-php-ext-install zip 

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

RUN curl -sS https://get.symfony.com/cli/installer | bash && mv /root/.symfony5/bin/symfony /usr/local/bin/symfony

WORKDIR /var/www

COPY . .

RUN composer install

CMD ["symfony", "serve", "--no-tls", "-d"]

I would appreciate any recommendations regarding the Dockerfile.

Reply

Hey Elijah,

We talked about running Symfony projects with Docker in e.g. this course: https://symfonycasts.com/screencast/symfony-doctrine - you can download the course code and pull some Docker-related files from the finish/ directory of it. Also, I would recommend you to watch a few first videos from that course to see how we work with it: https://symfonycasts.com/screencast/symfony-doctrine/install

I bet it will help you a lot :)

Cheers!

1 Reply
Elijah Avatar

Thx a lot!

Reply
RB_87 Avatar

Hello, is API Platform 3 compatible with Symfony 5.4?

Reply

Hey @RB_87

I'm afraid it's not compatible. In their composer.json I see they require Symfony 6 components https://github.com/api-platform/core/blob/main/composer.json
But, I may be wrong, the best way to know is by giving it a try :)

Cheers!

1 Reply
iclaborda Avatar
iclaborda Avatar iclaborda | posted hace 25 días

I followed those steps, however, I only get a 500 with "Unable to generate a URL for the named route "api_doc" as such route does not exist.", Don't know what to do...

Reply

Hey @iclaborda ,

What exactly steps? What commands did you run? composer require api? Please, make sure the recipe was executed in your console, usually Composer will ask you if you want to install the recipe and you should reply "Yes". Otherwise no config files will be created, and so it won't work our of the box unless you put all the config files yourself.

I'd recommend you to do composer remove api and then again: composer require api - but watch closer what Composer asks you - you will need to confirm installing the recipe, and also double check that you have all those config files after that we have in the video.

P.s. Also please, try to clear the cache just in case :)

Cheers!

Reply
ties8 Avatar

Hello,
I have not yet completed the course, so maybe i missed it
In the old course for API Platform 2, the creation of a Resource Metadata Factory was discussed. Since it is a very convenient way to create Metadata for inheritance structures (Bleu de Gex extends Blue Cheese extends Cheese) i would like to keep it after my migration to API Platform 3 and Symfony 6.
Is a video on the creation of the new or a replacement for the Resource Metadata Factory planned? Or generally, is the use of that approach even recommended with api platform 3?

Reply

Hey @ties8

In our recent ApiPlatform 3 tutorial we do not talk too much about customizing the docs but I think this video may help you out https://symfonycasts.com/screencast/api-platform-security/open-api-decoration
You can also check the ApiPlatform docs

Cheers!

Reply
ties8 Avatar

I am not sure if we are on the same page about what can be done with the Resource Metadata Factory in 2.6. Perhaps i should explain a bit further.
As far as i understood it, the Resource Metadata Factory generates the default values for what can then be modified inside the #[ApiResource] attribute set on every class.
So in 2.6 by decorating the Resource Metadata Factory i could once, dynamically, change the options which would normally be statically defined in every class inside the #[ApiResource] attribute. In your course "API Platform 2 Chapter 27" the system is used to dynamically set the normalization context instead of having to define it statically in the API Platform attribute on every class.
You can modify the CollectionOperations, ItemOperations, SubresourceOperations and other Attributes of the resource.
In my example of a inheritance structure i would have to define an #[ApiResource(...)] with the same content: short name, security ect. on every class which inherits from "Cheese". With a Resource Metadata Factory i avoid having to do that 3 times but can centralize it. The decorated Resource Metadata Factory checks if the resource it generates the metadata for is inheriting "Cheese" and then adjusts the data it generates accordingly.

I hope its now clear what i used the Metadata Factory for, if there is a video already available or in planning on how the stuff the Decorated Metadata Factory did is now done i would appreciate it if you could let me know.

Reply

Hey @ties8!

Yup, I know what you're talking about :). The short answer is that no, unfortunately, I decided not to cover this for the API Platform 3 tutorial. I just wasn't sure how many people were actually using it. But I can also say that, afaik, there is nothing that makes this now a "bad idea" in API Platform 3. The approach just needs to be updated for the config system. I can't say how to do it, as I haven't tried it. However, I don't think that the solution would be all that different. API Platform 3 still has this concept of "resource metadata collection factories" - here's the interface https://github.com/api-platform/core/blob/main/src/Metadata/Resource/Factory/ResourceMetadataCollectionFactoryInterface.php - and there are a bunch of them that use decoration to add more data. And you'll notice that interface looks identical to what we did in API Platform 2. So, this may just be a matter of adjusting your old interfaces and a few minor tweaks.

Btw, if you're successful (or not), I'd love to know!

Cheers!

Reply
ties8 Avatar

Starting my migration i found using "DoctrineOrmResourceCollectionMetadataFactory" was a good way to start. So far it seems to work, although i have not yet migrated my tests to v3.
As for using the Metadata Factory, first i use it for inheritance, one Metadata Factory sets all metadata for every child Resource and second for mass applying security to a part of an app. For example if i have 5 Resources only accessible to Premium Subscribers i can create and apply a "PremiumSubscriberResourceInterface" to all five of them and handle security centralized inside the Metadata Factory.

Reply

Woo! Sounds promising. And your use-case makes a lot of sense. This is one of those features where it feels like they probably shouldn't add something so automatic to the core of API Platform... but for certain projects, users can really leverage it.

Good luck!

Reply
CanadaGuy Avatar
CanadaGuy Avatar CanadaGuy | posted hace 6 meses | edited

I followed the demo instructions but without downloading the zip file that starts the project...

The demo won't work... I think its because the "src/Controller" folder is still empty when you just run the following:
composer create-project symfony/skeleton:"6.2.*" test
cd test
composer require api
composer require webonyx/graphql-php
composer require maker --dev

During the playback of the cast, I noticed there are 2 files in the Controller folder when you open and close the folder really quick, but there's no way to know what to put in those files.

My project only shows the simple "Welcome to Symfony 6.2.6" page, but adding /api to my URL gets me a 404 Not found. However running "bin/console debug:router" shows I am on the right path to getting something because the path names and info show up for "api_entrypoint", "api_doc", etc. but all those URLS get me a NOT FOUND.

Is there some key to the base "Controller" file that needs to be present that was skipped in the otherwise very nice tutorial?

Reply

Hey there,

I believe you're missing a few required packages that are absent from the symfony/skeleton project. Try creating a new project but installing symfony/webapp-pack

Cheers!

Reply
CanadaGuy Avatar

Thanks for the tip... That helped, but still had a problem, which in the end turned out to be a needed ".htaccess" file in the "public" folder (Running XAMPP on Windows) so it would perform the needed mod-rewrite rules forcing routes like /api to be directed into the index.php file instead of directly to apache (which of course could not find a /api folder under the public folder

Reply

Ohh, you're using XAMPP, I assumed you were using Symfony's web server. It does what you said under the hood :)

Reply
Michal-K Avatar
Michal-K Avatar Michal-K | posted hace 6 meses | edited

Hi! I have a question. Will this course work well with Symfony 5? :D
I mean, will it work the same as if it had Symfony 5? :D

Reply

Hey Michal!

Hmm. The problem is that API Platform 3 requires Symfony 6. So if you're using API Platform with Symfony 5, then I think you're using version 2.7, not 3. However, 2.7 and 3.0 are identical, except that deprecated items have been removed in 3.0. And, if you're using 2.7, you should set the metadata_backward_compatibility_layer flag to false - ref https://api-platform.com/docs/core/upgrade-guide/#im-migrating-from-26-and-want-to-prepare-for-30

If you do that, then yes, I think we very few exceptions, the tutorial will work fine for Symfony 5 and API Platform 2.7. If you hit any snags, you can let us know and we'll do our best to help!

Cheers!

1 Reply
vishajr Avatar

Hi Ryan, I just jumped into API Platform and it's pretty confusing to me.

I am planning to go through the API Platform 2 first since it has the security related content.

Is it okay or shall I just wait for API Platform 3 and start from there? Thanks!

Reply

Hey Vishajr,

The more you watch - the more you know ;) So, feel free to jump into ApiPlatform v2 tutorials first if you need it now, because releasing same tutorials on v3 will take some time. So it makes sense to start from those tutorials that are already recorded if you don't want to simply wait for new ones. But later, when v3 tutorials will be released - you can watch it again and I bet you will discover more new things for yourself, or even better understand it because you will have some base after old tutorials :)

Also, we added some notes in our v2 tutorials mentioning some differences and BC breaks, so it should help you as well ;)

Cheers!

Reply
kyotomano Avatar
kyotomano Avatar kyotomano | posted hace 6 meses

Hi! Is this course going to be divided into 3 parts just like api platform 2? [base, security, custom resources]. I also have more questions. Are you going to cover Mercure? When are you going to release all 3 parts (I read comment from SC team member who claimed that it would be released by the end of the year, but it was 3 months ago)? Btw. Great pick. V3 seems to be much different than V2

Reply

Hi kyotomano!

This is a perfect time to ask these questions :).

Is this course going to be divided into 3 parts just like api platform 2? [base, security, custom resources].

Probably, yes. Though there are a few things that I need to look into - like much better support in API Platform 3 for DTO objects - that might affect exactly what's in each episode or how we split it all up.

Are you going to cover Mercure?

I wasn't planning on it... at least not in any big way. But is that something you're interested with in regards to API Platform? What are you hoping to use it for?

When are you going to release all 3 parts (I read comment from SC team member who claimed that it would be released by the end of the year, but it was 3 months ago)? Btw. Great pick. V3 seems to be much different than V2

Yea :/. The conference and holidays slowed things down. I don't know when... but I'm really hoping to dive through all 3 as quickly as possible vs ep 1, a break, ep2, a break, ep 3, which I know is annoying for everyone.

If there are some specific things that you'd like to see in the more advanced tutorials, now is a great time to let me know!

Cheers!

1 Reply
kyotomano Avatar

Thanks for your great and detailed answer. No, no. I don't expect to see Mercure in any "heavy" way/use. But would be cool to see it in action with api platform - 2 maybe 3 episodes (just like in symfony ux tutorial). I just find Mercure an interesting part that wasn't covered in any tutorial before and Api platform seems just right place to do it. There is also lack of such content. You have symfony docs where they explain how to set it up (a little too much in my opinion, should be divided into parts like: docker, binary and then setup with example - quick setup and detailed setup like .yaml) and use, but there is a lack of real example usage. On Api Platform website is example of chat, but lack of repo on GitHub to check code to see how it works. There is only one YT tutorial that is outdated about Mercure (and based on that, many people in comments ask and complain about not being able to set it up and learn - cause there is indeed no learning resource except docs => check Laravel and pusher, there is a lot of examples and even whole tutorials about that topic on YT or Laracasts). That's why I asked about that.

Reply
Cat in space

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

What PHP libraries does this tutorial use?

// composer.json
{
    "require": {
        "php": ">=8.1",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "api-platform/core": "^3.0", // v3.0.8
        "doctrine/annotations": "^1.0", // 1.14.2
        "doctrine/doctrine-bundle": "^2.8", // 2.8.0
        "doctrine/doctrine-migrations-bundle": "^3.2", // 3.2.2
        "doctrine/orm": "^2.14", // 2.14.0
        "nelmio/cors-bundle": "^2.2", // 2.2.0
        "nesbot/carbon": "^2.64", // 2.64.1
        "phpdocumentor/reflection-docblock": "^5.3", // 5.3.0
        "phpstan/phpdoc-parser": "^1.15", // 1.15.3
        "symfony/asset": "6.2.*", // v6.2.0
        "symfony/console": "6.2.*", // v6.2.3
        "symfony/dotenv": "6.2.*", // v6.2.0
        "symfony/expression-language": "6.2.*", // v6.2.2
        "symfony/flex": "^2", // v2.2.4
        "symfony/framework-bundle": "6.2.*", // v6.2.3
        "symfony/property-access": "6.2.*", // v6.2.3
        "symfony/property-info": "6.2.*", // v6.2.3
        "symfony/runtime": "6.2.*", // v6.2.0
        "symfony/security-bundle": "6.2.*", // v6.2.3
        "symfony/serializer": "6.2.*", // v6.2.3
        "symfony/twig-bundle": "6.2.*", // v6.2.3
        "symfony/ux-react": "^2.6", // v2.6.1
        "symfony/validator": "6.2.*", // v6.2.3
        "symfony/webpack-encore-bundle": "^1.16", // v1.16.0
        "symfony/yaml": "6.2.*" // v6.2.2
    },
    "require-dev": {
        "doctrine/doctrine-fixtures-bundle": "^3.4", // 3.4.2
        "symfony/debug-bundle": "6.2.*", // v6.2.1
        "symfony/maker-bundle": "^1.48", // v1.48.0
        "symfony/monolog-bundle": "^3.0", // v3.8.0
        "symfony/stopwatch": "6.2.*", // v6.2.0
        "symfony/web-profiler-bundle": "6.2.*", // v6.2.4
        "zenstruck/foundry": "^1.26" // v1.26.0
    }
}
userVoice