Home > Back-end >  A different DTO between POST and PUT with API Platform
A different DTO between POST and PUT with API Platform

Time:10-04

I’m using Api Platform with DTOs. I’d like to understand if it is possible to have a field just in POST and not in PUT. In my use case I have a Customer that needs an email field, so that filed should be present for GET and POST. Anyway email should not be changed, so the field should not be present in PUT. This is the YAML file defining my resource:

App\Entity\Customer:
  attributes:
    input: 'App\DTO\CustomerInput'
    output: 'App\DTO\CustomerOutput'
  collectionOperations:
    get:
      path: /customer
    post:
      path: /customer
  itemOperations:
    get:
      path: /customer/{fiscalId}
    put:
      path: /customer/{fiscalId}

And this is the input DTO:

class CustomerInput
{
    public string $fiscalId;
    public string $email;
    public string $businessName;
}

The main problem I have is not to expose the email field as a valid input field for POST in the Open API documentation. Thanks in advance!

CodePudding user response:

First I think you should specify which version of api-platform you're using, because the way that DTO are handled has changed between the version 2.6 and 2.7. So if you are using 2.6 or below, you can specify custom input and output per operation like this (Api Platform docs):

App\Entity\Book:
  collectionOperations:
    create:
      method: POST
      input: App\Dto\CreateBook
      output: App\Dto\BookOutput
  itemOperations:
    update:
      method: PUT
      input: App\Dto\UpdateBook
      output: App\Dto\BookOutput
  • Related