Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API Platform - Invalid value provided (invalid IRI?). How to POST with relations?

I setup a pretty straightforward Group -> GroupUser -> User relationship (GroupUser being a join table with additional data fields, Group OneToMany GroupUsers, which has ManyToOne Group and User, and User with OneToMany GroupUser) and fail to POST to the API, receiving an invalid IRI error. There seems to be quite some confusion about this, I found several posts (here and here) on this but none clearly addresses my most basic scenario (I followed the API platform documentation and have a Symfony4 with a require api-platform/api-pack installation).

I am using IRI to associate the objects, but the following POST does not work (I do have a user with id 1 and a group with id 1) and returns the Invalid value provided (invalid IRI?) error:

curl -X POST "http://api.platform.local/group_users" -H "accept: application/ld+json" -H "Content-Type: application/ld+json" -d "{ \"group\": \"/groups/1\", \"user\": \"/users/1\", \"role\": \"member\"}"

Here are my entities:

App/Entity/Group

/**
 * @ORM\OneToMany(targetEntity="GroupUser", mappedBy="group")      
 */
private $users;

App/Entity/User

/**
 * @ORM\OneToMany(targetEntity="GroupUser", mappedBy="user")
 */
private $groups;

App/Entity/GroupUser

/**
 * @Assert\NotBlank
 * @ORM\JoinColumn(
 *     nullable=false,
 *     onDelete="CASCADE"
 * )
 * @ORM\ManyToOne(
 *    inversedBy="users",
 *    targetEntity="App\Entity\Group"
 * )
 */
private $group;

/**
 * @Assert\NotBlank
 * @ORM\JoinColumn(
 *     nullable=false,
 *     onDelete="CASCADE"
 * )
 * @ORM\ManyToOne(
 *     inversedBy="groups",
 *     targetEntity="App\Entity\User"
 * )
 */
private $user;

I must be missing something fundamental, but the documentation doesn't seem to require anything else. This post didn't help, I even added an id to the UserGroup entity just for that, initially I only had user and group as table ids.

Your help is appreciated, many thanks beforehand.

like image 888
c7nj7n Avatar asked Sep 15 '25 17:09

c7nj7n


1 Answers

I finally figured this out, actually I made two mistakes:

  1. I passed values to __construct to populate a GroupUser upon construction. I removed the __construct entirely, this didn't play nice with the API Platform and the automatic IRI creation.

  2. I used a composite primary key on group_id and user_id for my GroupUser table, which I abandoned in favour of an own ID.

Pretty straight forward, here's what I added to the GroupUser entity:

  /**
   * @var int
   *
   * @ORM\Column(type="integer")
   * @ORM\GeneratedValue(strategy="AUTO")
   * @ORM\Id
   */
  private $id;  

And don't forget the getter method:

  public function getId(): ?int
  {
    return $this->id;
  }
like image 172
c7nj7n Avatar answered Sep 17 '25 19:09

c7nj7n