简体   繁体   中英

How do you make symfony make:crud available for API's?

In symfony you can use the command make:crud . That works excellent with forms and twig in symfony. But is there also a way to do it with api's? That I will send an POST to the route of the annotation.

Like in python;

url = 'https://127.0.0.1:8000/players/new'
myobj = {
    'postName': 'postData',
    }

This python code is used when i want to test a POST.

This is a piece of a make:crud what i used, only showing the New function of the CRUD. This only works with forms. I cant send directly a POST(ex, python) to it.

/**
 * @Route("/players/new", name="players_new", methods={"GET","POST"})
 */
public function new(Request $request): Response
{
    $player = new Players();
    $form = $this->createForm(PlayersType::class, $player);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($player);
        $entityManager->flush();

        return $this->redirectToRoute('players_index');
    }

    return $this->render('players/new.html.twig', [
        'player' => $player,
        'form' => $form->createView(),
    ]);
}

As per the official documentation, API platform is a “powerful but easy to use full-stack framework dedicated to API driven projects”. API platform helps developers significantly speed up their development process, building complex and high performance, hypermedia-driven APIs.

It ships with Symfony 4, the Doctrine ORM, a dynamic Javascript admin created with React, and React Admin, Varnish Cache server, Helm Chart to help deploy the API in a Kubernetes cluster and a Progressive Web Application skeleton. It also includes a Docker setup for providing Nginx servers to run the API and JavaScript apps. Most inspiring is the ability of API platform to natively generate project documentation with support of OpenAPI!

In this tutorial, I will take you through how to create a simple bucket list API with CRUD operations. Prerequisites

    PHP - Version 7.0 or higher.
    Docker
    Postgres

Getting Started

Follow the instructions below to setup your development environment:

$ mkdir demo-app
$ cd demo-app

Download the latest compressed.tar.gz distribution. Then extract it inside of our working directory and run the commands below:

$ cd api-platform-2.4.5
$ docker-compose pull
$ docker-compose up -d

The docker-compose pull command downloads all images specified in the docker-compose.yml file. In order to start the containers, run docker-compose up -d. The -d flag runs the containers in detached mode, meaning they run in the background. In order to view the container logs, you can run this command docker-compose logs -f in a separate terminal.

I changed your endpoint slightly to make it more API friendly. In all the public facing APIs that I've built they all return JSON. That just eases the burdens for implementation. I always use a status 201 for creation, and 400 for bad requests. This serves a traditional role for RESTful API paradigms and implementations.

    /**
     * @Route("/players/{player}", name="get_player", methods={"GET"})
     */
    public function getPlayer(Player $player): Response {
        // You might need to tweak based on your Entity name
        return new JsonResponse($player);
    }
    
    /**
     * @Route("/players/new", name="players_new", methods={"POST"})
     */
    public function newPlayer(Request $request): Response
    {
        $player = new Players();
        $form = $this->createForm(PlayersType::class, $player);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            try {
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->persist($player);
                $entityManager->flush();
            } catch (\Exception $e) {
                // Probably a better exception to catch here, log it somewhere
                throw $e;
            }
            
            return new JsonResponse('', Response::HTTP_CREATED);
        }
        
        return new JsonResponse(
            'Invalid data provided to API, please refer to documentation', 
            Response::HTTP_BAD_REQUEST
        );
    }

Changing the method from new to newPlayer was done because a method named new is confusing down the road. One thing I would also like to point out is that with Doctrine it's best to have your entities singular. Example: Player instead of Players . You can have the relationship be players within the Entity.

The Entity Game could have $players which is a relationship to OneToMany Player Entities.

Catching the exception on flush is good standard practice there. You should return a meaningful JsonResponse as well after you've logged it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM