Giter Club home page Giter Club logo

api-platform's Introduction

API Platform

API Platform is a next-generation web framework designed to easily create API-first projects without compromising extensibility and flexibility:

The official project documentation is available on the API Platform website.

API Platform embraces open web standards and the Linked Data movement. Your API will automatically expose structured data. It means that your API Platform application is usable out of the box with technologies of the semantic web.

It also means that your SEO will be improved because Google leverages these formats.

Last but not least, the server component of API Platform is built on top of the Symfony framework, while client components leverage React (Vue.js flavors are also available). It means that you can:

  • Use thousands of Symfony bundles and React components with API Platform.
  • Integrate API Platform in any existing Symfony, React, or Vue application.
  • Reuse all your Symfony and JavaScript skills, and benefit from the incredible amount of documentation available.
  • Enjoy the popular Doctrine ORM (used by default, but fully optional: you can use the data provider you want, including but not limited to MongoDB and Elasticsearch)

Install

Read the official "Getting Started" guide.

Credits

Created by Kévin Dunglas. Commercial support is available at Les-Tilleuls.coop.

api-platform's People

Contributors

alanpoulain avatar amenophis avatar beerfranz avatar beyerjc avatar bharatr21 avatar chris53897 avatar darthf1 avatar dependabot[bot] avatar dunglas avatar fabious avatar francislavoie avatar gaetan-petit avatar ginifizz avatar gregoirehebert avatar ili101 avatar jenaye avatar jfcoz avatar krismas avatar lctrs avatar meyerbaptiste avatar pborreli avatar simperfit avatar slipo avatar soyuka avatar sroze avatar strikerrus avatar teohhanhui avatar theofidry avatar toofff avatar vincentchalamon avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

api-platform's Issues

How to contribute

Hello @dunglas ,

I really like the work you've done with api-platform.
I'd like to know what is the roadmap and how can I help to make it better ?

Thx,

Cheers,

Baptiste

[meta] The road to 1.0

The roadmap:

DunglasApiBundle:

  1. Improve the quality (fix issues raised by Scrutinizr https://scrutinizer-ci.com/g/dunglas/DunglasApiBundle/ a notation > 9/10 is the goal)
  2. Increase the unit test coverage (both in DunglasApiBundle, > 80% is the goal), needed for php-schema too. Existing unit tests must also be refactored: external libraries must not ne mocked anymore and value objects must be used directly, not mocked.
  3. Implement the ADR pattern instead of current controllers api-platform/core#191
  4. Decouple from Hydra api-platform/core#191
  5. Rename Resource to ResourceType and make it immutable as done for metadata (api-platform/core#180). As they are value object, their interface can be removed.
  6. Enhance the configuration system: create a @Resource and @Operation annotation
  7. Isolate the Symfony related code (the bundle class, the configuration and dependency injection related code) to make api platform an isolated library (but still usable easily with Symfony)
  8. Last but not least, move every repositories to the org https://github.com/api-platform and change namespace of all projects from Dunglas to ApiPlatform

The renaming will be:

  • dunglas/api-platform-doc -> api-platform/doc
  • dunglas/DunglasApiBundle -> api-platform/core / ApiPlatform\Core
  • dunglas/php-schema -> api-platform/schema-generator ApiPlatform\SchemaGenerator
  • dunglas/php-property-info -> api-platform/property-info ApiPlatform\PropertyInfo
  • dunglas/api-platform-heroku -> api-platform/heroku-integration ApiPlatform\Heroku
  • dunglas/blog-api -> api-platform/demo-blog-api
  • dunglas/blog-client -> api-platform/demo-blog-client-angular
  • [ ](maybe, I need to think more about that) dunglas/DunglasAngularCsrfBundle -> api-platform/ApiPlatformSpaCsrfBundle / ApiPlatform\Bundle\SpaCsrf

Maybe can we integrate @theofidry's https://github.com/theofidry/LoopBackApiBundle and @vincentchalamon's https://github.com/vincentchalamon/docker-symfony under the api-platform org too

Some non-coding tasks are also in progress:

Our focus is currently on ApiBundle, some architecture changes are in progress: https://github.com/dunglas/DunglasApiBundle/issues

No resource found for object of type ...

No resource found for object of type "AppBundle\Entity\User\Admin"
I get this error when try to use single table inheritance.
Here is my entity:

namespace AppBundle\Entity\User;

use Doctrine\ORM\Mapping as ORM;
use Dunglas\ApiBundle\Annotation\Iri;
use Symfony\Component\Validator\Constraints as Assert;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * A person (alive, dead, undead, or fictional).
 *
 * @see http://schema.org/Person Documentation on Schema.org
 *
 * @Iri("http://schema.org/Person")
 *
 * @ORM\Entity
 * @ORM\Table("User")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="type", length=15, type="string")
 * @ORM\DiscriminatorMap(
 *     {
 *     "admin"="AppBundle\Entity\User\Admin",
 *     "customer"="AppBundle\Entity\User\Customer",
 *     "farmer"="AppBundle\Entity\User\Farmer"
 *     }
 * )

 * @UniqueEntity("email")
 * @UniqueEntity("username")
 */
abstract class User extends BaseUser
{
    /**
     * @var int
     *
     * @ORM\Column(type="guid")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     */
    protected $id;
    /**
     * @var string The username of the author.
     *
     * @Groups({"user_read", "user_write"})
     */
    protected $username;

    /**
     * @var string The email of the user.
     *
     * @Groups({"user_read", "user_write"})
     */
    protected $email;
}

Is there any workaround to handle this ?

Float assert not working properly

I have property $age with assert type "float" in my entity. When I try to make POST request with age for example "2" i get response "age: This value should be of type float." How to do this working? Every value causes this error. Can I use such assertions in my entity?

Adding fixtures

Should we add some fixtures out of the box to allow the user to see how the application behave (and not an empty database)?

cc @dunglas

Explain errors when request is not valid

I ran into this time, for example I'm trying to create new entity sending POST request and put invalid json (or forgot put the json at all), then I got not really informative response

{
"@context": "/api/contexts/Error",
"@type": "Error",
"hydra:title": "An error occurred",
"hydra:description": "Syntax error",
"trace": [
{
"function": "cpostAction",
"class": "Dunglas\ApiBundle\Controller\ResourceController",
"type": "-\u003E",
"args": [
{
"attributes": {},
"request": {},
"query": {},
"server": {},
"files": {},
"cookies": {},
"headers": {}
}
]
},
{
"file": "/var/www/v3/app/bootstrap.php.cache",
"line": 3210,
"function": "call_user_func_array",
"args": [
[
{},
"cpostAction"
],
[
{
"attributes": {},
"request": {},
"query": {},
"server": {},
"files": {},
"cookies": {},
"headers": {}
}
]
]
},

It would be great to get message which explains me that the json is invalid.

Add multiple entity manager

Hello,
i try to use multiple entity manager doctrine but i can't find any documentation about this. This is the doctrine entity declaration.

    doctrine:
        dbal:
        default_connection: es
                connections:
                    es:
                        driver:   "%database_driver%"
                        host:     "%database_host%"
                        port:     "%database_port%"
                        dbname:   "happy_es"
                        user:     "%database_user%"
                        password: "%database_password%"
                        charset:  UTF8

                    pt:
                        driver:   "%database_driver%"
                        host:     "%database_host%"
                        port:     "%database_port%"
                        dbname:   "happy_pt"
                        user:     "%database_user%"
                        password: "%database_password%"
                        charset:  UTF8
            orm:
                default_entity_manager: es
                entity_managers:
                    es:
                        connection: es
                        mappings:
                            AppBundle: ~
        dql:
                            datetime_functions:
                                date:           Oro\ORM\Query\AST\Functions\SimpleFunction
                                time:           Oro\ORM\Query\AST\Functions\SimpleFunction
                            numeric_functions:
                                timestampdiff:  Oro\ORM\Query\AST\Functions\Numeric\TimestampDiff
                                day:            Oro\ORM\Query\AST\Functions\SimpleFunction
                                hour:           Oro\ORM\Query\AST\Functions\SimpleFunction
                                minute:         Oro\ORM\Query\AST\Functions\SimpleFunction
                                second:         Oro\ORM\Query\AST\Functions\SimpleFunction
                    pt:
                        connection: pt
                        mappings:
                            AppBundle: ~
        dql:
                            datetime_functions:
                                date:           Oro\ORM\Query\AST\Functions\SimpleFunction
                                time:           Oro\ORM\Query\AST\Functions\SimpleFunction
                            numeric_functions:
                                timestampdiff:  Oro\ORM\Query\AST\Functions\Numeric\TimestampDiff
                                day:            Oro\ORM\Query\AST\Functions\SimpleFunction
                                hour:           Oro\ORM\Query\AST\Functions\SimpleFunction
                                minute:         Oro\ORM\Query\AST\Functions\SimpleFunction
                                second:         Oro\ORM\Query\AST\Functions\SimpleFunction

Use instruction missing on QualitativeValue's children

The instruction

use SchemaOrg\Enum\QualitativeValue;

is missing in the QualitativeValue's children.

Example of generation with CarUsageType

The command

username:~/path/to/project$ php app/console doctrine:schema:update

cause this error

PHP Fatal error: Class 'AppBundle\Entity\QualitativeValue' not found in /home/username/path/to/project/src/AppBundle/Entity/CarUsageType.php on line 17
[2015-10-11 17:27:49] php.CRITICAL: Fatal Error: Class 'AppBundle\Entity\QualitativeValue' not found {"type":1,"file":"/home/username/path/to/project/src/AppBundle/Entity/CarUsageType.php","line":17,"level":-1,"stack":[]}

Add

use SchemaOrg\Enum\QualitativeValue;

fix the problem but you have to do it after each generation for each child.

Provide a Docker Compose setup

Looking at #49, I think we should provide a complete Docker Compose setup.

Do you think it should be in a separate repo? I'll see if I can contribute mine as a start.

support propel

Hello, does api-platform support propel?

enjoy the popular Doctrine ORM (used by default, but fully optional: you can use the data provider you want, including but not limited to MongoDB ODM and ElasticSearch)

No resource found for object of type one to many relation

hydra:description: "No resource found for object of type "AppBundle\Document\article"",
i have two mongo db documents user and article and each user has multiple articles so i'm trying to list all the users with all their articles titles so i can get something like this :

{
@id: "/user/53edb6200cf2400d584c2617",
@type: "user",
class: "de.freelancer.mongo.domain.User",
email: "[email protected]",
displayname: "feer",
withnewsletter: false,
language: "de_DE",
active: true,
admin: false,
articles : ['article1','article2','article3']
}

here is my code :

*user Document *

`<?php
namespace AppBundle\Document;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Dunglas\ApiBundle\Annotation\Iri;
use Symfony\Component\Validator\Constraints as Assert;
/**

  • @mongodb\Document

  • @mongodb\Document(collection="user")
    /
    class User
    {
    /
    *

    • @mongodb\Id(strategy="AUTO")
      */
      private $id;

    /**

    • @mongodb\ReferenceMany(targetDocument="articles", mappedBy="user")
      */
      private $articles;

    public function __construct()
    {
    $this->articles = new ArrayCollection();
    }

    /**
    */
    public function getArticles()
    {
    return $this->articles;
    }
    }`

*articles document : *

`<?php

namespace AppBundle\Document;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Dunglas\ApiBundle\Annotation\Iri;
use Symfony\Component\Validator\Constraints as Assert;

/**

  • @mongodb\Document

  • @mongodb\Document(collection="article")
    /
    class article
    {
    /
    *

    • @mongodb\Id(strategy="AUTO")
      */
      private $id;

    /**

    • @mongodb\ReferenceOne(targetDocument="user", inversedBy="articles")
      */
      private $user;

    /**

    */
    public function setUser(userProfile $user)
    {
    $this->user = $user;
    return $this;
    }

    /**

    */
    public function getUser()
    {
    return $this->user;
    }

}
`
can any one help me to get the list of the user articles

thanks

Missing step on getting started documentation (Symfony cache clear)

In "Creating your first API with API Platform" documentation, there is a missing step.
After exposing the API, you must clean Symfony cache.

php app/console cache:clear

If this step is not performed, the server does not find the new API routes.
I know it's silly, but can save you a few minutes of confusion.

EasyRdf_Graph not finding any resources

Following https://api-platform.com/doc/1.0/getting-started/api

lsmith@pooteeweet blog-api ((v1.0.0))$ bin/schema generate-types src/ app/config/schema.yml --verbose
[critical] Type "BlogPosting" cannot be found.
[critical] Type "Article" cannot be found.
[critical] Type "CreativeWork" cannot be found.
[critical] Type "Thing" cannot be found.
[critical] Type "Person" cannot be found.

lsmith@pooteeweet blog-api ((v1.0.0))$ cat app/config/schema.yml
# app/config/schema.yml

annotationGenerators: # Generators we want to use, keep it as is for any API Platform project
    - ApiPlatform\SchemaGenerator\AnnotationGenerator\PhpDocAnnotationGenerator
    - ApiPlatform\SchemaGenerator\AnnotationGenerator\DoctrineOrmAnnotationGenerator
    - ApiPlatform\SchemaGenerator\AnnotationGenerator\ConstraintAnnotationGenerator
    - ApiPlatform\SchemaGenerator\AnnotationGenerator\DunglasApiAnnotationGenerator
namespaces:
  entity: AppBundle\Entity # The default namespace for entities, following API Platform and Symfony best practices
types: # The list of type to generated (a PHP entity class by type will be generated)
  BlogPosting: ~ # A type to generate a PHP entity class from, including all its properties (here this type has no specific property, they are all inherited)
  Article: # Schema.org has an inheritance system, we will configure all types of the hierarchy
    properties: # The list of properties we want to use
      articleBody: ~
      articleSection: ~
  CreativeWork:
    properties:
      author:
        range: Person # PHP Schema handle relations. Here we force the type of the property to Person
        cardinality: (*..0) # Force the cardinality of the relation
      headline: ~
      isFamilyFriendly: ~
      datePublished: ~
  Thing:
    properties:
      name: ~
  Person: # Person is a relation of the "CreativeWork" type (property "author"), PHP Schema will generate relations for us
    properties: {} # We don't want any specific property for a person except "name" inherited from Thing

Behat version and Given issue

I've got some error with basic behat scenario

  @createSchema
  Scenario: Create a Person
    Given Abc

where Behat send a Exception

[Behat\Mink\Exception\DriverException]                
  Unable to access the response before visiting a page

It's a Behatch version problem. dev-master works fine where ~2.1 breaks. The Behatch version in DunglasApiBundle is already set to dev-master. I don't see this as a good practice but it could be a temporary solution for api-platform too.

There's also reference to this issue here

docker-compose failed

I don't run docker-compose.

After

git clone git clone https://github.com/api-platform/api-platform.git 
cd api-platform
docker-compose up

I have this error :

Step 9 : RUN ((rm -rf var/cache/* && rm -rf var/logs/* && rm -rf var/sessions/*) || true)     && composer install -o && app/console cache:warmup -e=prod     && chown -R www-data . var/cache var/logs var/sessions
 ---> Running in e1fcd8cad2a8
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
    Failed to download willdurand/negotiation from dist: The zip extension and unzip command are both missing, skipping.
The php.ini used by your command-line PHP is: /usr/local/etc/php/php.ini
    Now trying to download from source
  - Installing willdurand/negotiation (v2.0.2)
    Cloning a8ce6da7acdf07351ccd6a9359c571ebc0725a21


  [RuntimeException]                                                                                                                  
  Failed to clone https://github.com/willdurand/Negotiation.git, git was not found, check that it is installed and in your PATH env.  
  sh: 1: git: not found                                                                                                               


install [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--no-plugins] [--no-custom-installers] [--no-autoloader] [--no-scripts] [--no-progress] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--ignore-platform-reqs] [--] [<packages>]...

ERROR: Service 'web' failed to build: The command '/bin/sh -c ((rm -rf var/cache/* && rm -rf var/logs/* && rm -rf var/sessions/*) || true)     && composer install -o && app/console cache:warmup -e=prod     && chown -R www-data . var/cache var/logs var/sessions' returned a non-zero code: 1

Error removing Persons from the Book entity

If I try to remove Persons from a Book I get the following error:

PUT http://localhost:9000/books/1
Content-Type: application/json
{
    "name": "Book 1", 
    "illustrator": [],
    "author": []
}
 -- response --
400 Bad Request
...
 "array_search() expects parameter 2 to be array, object given",
    "api-platform/src/AppBundle/Entity/Book.php", 106
    and 
    "api-platform/src/AppBundle/Entity/CreativeWork.php", 95,
...

This occurs because a Doctrine\ORM\PersistentCollection is passed as a second argument.

I fixed it and made a pull request #22

robots.txt and icons in /web folder

Hi

Why do the framework stores these resources? They must be stored in the frontend.
By the way there is no point to have this web folder anymore.

Documentation for custom operation

I have some operation, which allows me to add, edit and delete additional phones, emails and addresses for user. Here is example of operation:

 resource.user_telephone.item_operation.put:
    class:   "Dunglas\ApiBundle\Api\Operation\Operation"
    public:  false
    factory: [ "@api.operation_factory", "createItemOperation" ]
    arguments:
      -    "@resource.user"      # Resource
      -    [ "PUT" ]                  # Methods
      -    "/users/{id}/phones/"     # Path
      -    SIPApiBundle:User:additionalTelephonePut  # Controller
      -    "user_additional_telephone_put"      # Route name
      -
        "@type": "hydra:Operation"
        "hydra:title": "Edit additional phone Operation"
        "returns": "xmls:string"

And here is my resource

resource.user:
    parent:    "api.resource"
    arguments: [ "SIP\ResourceBundle\Entity\User\User" ]
    calls:
      - method:    "initNormalizationContext"
        arguments: [ { groups: [ "user_read" ] } ]
      - method:    "initDenormalizationContext"
        arguments: [ { groups: [ "user_write" ] } ]
      - method:    "initCollectionOperations"
        arguments:
          -
            - @resource.user_email.item_operation.put
            - @resource.user.collection_operation.post
            - @resource.user.collection_operation.get
            - @resource.user_collections.current_user
            - @resource.user_telephone.collection_operation.post
            - @resource.user_telephone.item_operation.put
            - @resource.user_telephone.item_operation.delete
            - @resource.user_email.collection_operation.post
            - @resource.user_email.item_operation.delete
            - @resource.user_address.collection_operation.post
            - @resource.user_address.item_operation.put
            - @resource.user_address.item_operation.delete
      - method:    "initFilters"
        arguments:
          -
           - @resource.user.search_filter
           - @resource.user.order_filter
    tags:      [ { name: "api.resource" } ]

How can i override generated documentation, because it is incorrect for my method. I don`t need so much parameters. Also the title for method is generated by the firs declareted method, not for each one individually.

Nitpicking: array_search with ArrayCollection

It may works fine but I still get a warning in my IDE with:

public function removeIllustrator(Person $illustrator)
{
    $key = array_search($illustrator, $this->illustrator, true);
    if (false !== $key) {
        unset($this->illustrator[$key]);
    }

    return $this;
}

Changing $this->illustrator to $this->illustrator->toArray() solves the problem. Or maybe using the property of ArrayCollection:

public function removeIllustrator(Person $illustrator)
{
    if ($this->mandates->contains($mandate)) {
        $this->mandates->removeElement($mandate);
    }

    return $this;
}

I should be able to build Docker environment whatever project issues

I'm currently trying to implement this project Docker configuration in my project using API Platform 2. I may have some issues on my project as it's still in development (so I could have some issues running Symfony commands like cache:clear).

As Dockerfile runs composer install, it will try to execute some Symfony commands, which will fail, which will block my Docker build.

Dockerfile should not execute any Composer or Symfony commands, to be able to create a correct Docker environment without project dependencies.

Normalization context

Hi,
Currently the API Bundle lets you specify a group serialization through the service of a resource.

services:
    resource.person:
        parent:     api.resource
        tags:       [ { name: api.resource } ]
        arguments:  [ AppBundle\Entity\Person ]
        calls:
            - [ initNormalizationContext, [ { groups: [ list ] } ] ]

The problem is that the method initNormalizationContext is applied to all operations on items and collections.

If for example in a person list, we need to display only the givenName and familyName, we apply the list group. yet in the person detail page we need more informations: birhtDate, telephone etc. and we want to add the detail group.

namespace AppBundle\Entity;

use ...

/**
 * A person (alive, dead, undead, or fictional).
 * 
 * @see http://schema.org/Person Documentation on Schema.org
 * 
 * @ORM\MappedSuperclass
 * @Iri("http://schema.org/Person")
 */
abstract class Person extends Thing
{
    /**
     * @var string Family name. In the U.S., the last name of an Person. This can be used along with givenName instead of the name property.
     * ...
     * @Groups({"list", "detail"})
     */
    private $familyName;

    /**
     * @var string Given name. In the U.S., the first name of a Person. This can be used along with familyName instead of the name property.
     * ...
     * @Groups({"list", "detail"})
     */
    private $givenName;

    /**
     * @var \DateTime Date of birth.
     * ...
     * @Groups({"detail"})
     */
    private $birthDate;

    /**
     * @var string The telephone number.
     * ...
     * @Groups({"detail"})
     */
    private $telephone

I see 2 solutions:

1. Use the api.retrieve event
<?php
namespace AppBundle\EventListener;

use Dunglas\ApiBundle\Event\DataEvent;

class MyEventListener
{
    /**
     * @param DataEvent $dataEvent
     */
    public function onRetrieve(DataEvent $dataEvent)
    {
        $resource = $dataEvent->getResource();

        $resource->initNormalizationContext(array_merge(
            $resource->getNormalizationGroups(),
            ['detail']
        ));
    }

Define the service:

services:
    my_event_listener:
        class: "AppBundle\EventListener\MyEventListener"
        tags:  [ { name: kernel.event_listener, event: api.retrieve, method: onPostCreate } ]
2. Use initItemOperations and override item_operation.get via a controller:
<?php
namespace AppBundle\Controller;

use Dunglas\ApiBundle\Controller\ResourceController;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class OperationController
 * @package AppBundle\Controller
 */
class CustomController extends ResourceController
{
    /**
     * @param Request $request
     * @param int $id
     *
     * @return \Dunglas\ApiBundle\JsonLd\Response
     */
    public function getAction(Request $request, $id)
    {
        $resource = $this->getResource($request);

        $resource->initNormalizationContext(array_merge(
            $resource->getNormalizationGroups(),
            ['detail']
        ));

        return parent::getAction($request, $id);
    }
}

Define the service:

services:
    resource.person:
        parent:     api.resource
        tags:       [ { name: api.resource } ]
        arguments:  [ AppBundle\Entity\Person ]
        calls:
            - [ initNormalizationContext, [ { groups: [ list ] } ] ]
            - [ initItemOperations, [ [ @resource.person.item_operation.get ] ] ]

    resource.person.item_operation.get:
        public: false
        class: Dunglas\ApiBundle\Api\Operation\Operation
        factory: [ @api.operation_factory, createItemOperation ]
        arguments: [ @resource.person, [ GET ], null, AppBundle:Custom:get ]

Both solutions works, but it's an assault course for add a simple serialization group.

Symfony 3

Hello,

To begin, thanks for this usefull project.
My question is : Have you a planning for adapt api-platform to Symfony 3?

Best Regards,

Fresh create-project install schema generator without custom RDFa support.

After following successfully the tutorial here, I intended to create my very own RDFa declaration and play with it.

When launching the schema command, I got Type "QuestionTest" cannot be found., and ended up looking at my composer, found out that schema-generator is fixed to v1.0.0.

You need to update to dev-master to leverage the new vocabularyNamespace schema key, which is not obvious when reading the tutorial. Hope it'll help someone.

Issue with EasyRDF Parser when rdfa file confguration as default value

Hi,

At the beginning, thx for project and contribution.

I have an issue with EasyRDF Parser,

when i omit use the RDFA file configuration to use default value (http://schema.org/docs/schema_org_rdfa.html) i got this error :

PHP Warning:  DOMDocument::loadHTML() expects parameter 1 to be a valid path, string given in /app/vendor/easyrdf/easyrdf/lib/EasyRdf/Parser/Rdfa.php on line 701
PHP Stack trace:
PHP   1. {main}() /app/vendor/dunglas/php-schema/bin/schema:0
PHP   2. Symfony\Component\Console\Application->run() /app/vendor/dunglas/php-schema/bin/schema:27
PHP   3. Symfony\Component\Console\Application->doRun() /app/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:126
PHP   4. Symfony\Component\Console\Application->doRunCommand() /app/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:195
PHP   5. Symfony\Component\Console\Command\Command->run() /app/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:878
PHP   6. SchemaOrgModel\Command\GenerateTypesCommand->execute() /app/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:259
PHP   7. EasyRdf_Graph->load() /app/vendor/dunglas/php-schema/src/SchemaOrgModel/Command/GenerateTypesCommand.php:70
PHP   8. EasyRdf_Graph->parse() /app/vendor/easyrdf/easyrdf/lib/EasyRdf/Graph.php:341
PHP   9. EasyRdf_Parser_Rdfa->parse() /app/vendor/easyrdf/easyrdf/lib/EasyRdf/Graph.php:234
PHP  10. DOMDocument->loadHTML() /app/vendor/easyrdf/easyrdf/lib/EasyRdf/Parser/Rdfa.php:701

Warning: DOMDocument::loadHTML() expects parameter 1 to be a valid path, string given in /app/vendor/easyrdf/easyrdf/lib/EasyRdf/Parser/Rdfa.php on line 701

Call Stack:
    0.0001     235200   1. {main}() /app/vendor/dunglas/php-schema/bin/schema:0
    0.0064    1656896   2. Symfony\Component\Console\Application->run() /app/vendor/dunglas/php-schema/bin/schema:27
    0.0079    1992320   3. Symfony\Component\Console\Application->doRun() /app/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:126
    0.0080    1993240   4. Symfony\Component\Console\Application->doRunCommand() /app/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:195
    0.0080    1993744   5. Symfony\Component\Console\Command\Command->run() /app/vendor/symfony/symfony/src/Symfony/Component/Console/Application.php:878
    0.0081    1998200   6. SchemaOrgModel\Command\GenerateTypesCommand->execute() /app/vendor/symfony/symfony/src/Symfony/Component/Console/Command/Command.php:259
    0.0149    3365640   7. EasyRdf_Graph->load() /app/vendor/dunglas/php-schema/src/SchemaOrgModel/Command/GenerateTypesCommand.php:70
    0.2599    3785400   8. EasyRdf_Graph->parse() /app/vendor/easyrdf/easyrdf/lib/EasyRdf/Graph.php:341
    0.2607    3947600   9. EasyRdf_Parser_Rdfa->parse() /app/vendor/easyrdf/easyrdf/lib/EasyRdf/Graph.php:234
    0.2611    4000592  10. DOMDocument->loadHTML() /app/vendor/easyrdf/easyrdf/lib/EasyRdf/Parser/Rdfa.php:701

I've look thought EasyRDF, they use your own http client, there are a issue to use guzzle and follow PSR-7 but always in progress cf : easyrdf/easyrdf#133

Do you have any recommendation, or can you do up the EasyRDF issue ?

Thx a lot for your time.

Serious limitations trying to mimic schema.org hierarchy with Doctrine ORM inheritance

Consider this scenario:

// src/AppBundle/Entity/Thing.php
namespace AppBundle\Entity;

use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Dunglas\ApiBundle\Annotation\Iri;

/**
 * The most generic type of item.
 *
 * @see http://schema.org/Thing Documentation on Schema.org
 *
 * @ORM\MappedSuperclass
 * @Iri("http://schema.org/Thing")
 */
abstract class Thing
{
    /**
     * @var Collection<ImageObject> An image of the item. This can be a [URL](http://schema.org/URL) or a fully described [ImageObject](http://schema.org/ImageObject).
     *
     * @ORM\ManyToMany(targetEntity="ImageObject")
     * @Iri("http://schema.org/image")
     */
    private $image;
}
// src/AppBundle/Entity/ImageObject.php
namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Dunglas\ApiBundle\Annotation\Iri;

/**
 * An image file.
 *
 * @see http://schema.org/ImageObject Documentation on Schema.org
 *
 * @ORM\Entity
 * @Iri("http://schema.org/ImageObject")
 */
class ImageObject extends MediaObject
{
}

(CreativeWork and MediaObject omitted for brevity)

This breaks down whenever there's more than one entity extending from Thing (well, of course...)

[documentation] Missing SocialMediaPosting in schema.yml

Hi,
the official documentation "Creating your first API with API Platform" is missing SocialMediaPosting: ~ under types key in schema.yml.
This leads to the error message while generating entities:

$ bin/schema generate-types src/ app/config/schema.yml 
[error] The type "SocialMediaPosting" (parent of "BlogPosting") doesn't exist

ng-admin issue

Hello,

Imported ng-admin inside my angular project from repo https://github.com/api-platform/admin.

Before ng-admin import, project was working with demo angularclient project and demo blog api-platform from Symfony.

All bower requirements are installed.

Find here project files

As results, I got blank page displayed and 5 remaining warnings :

Running "newer:jshint:all" (newer) task

Running "jshint:all" (jshint) task

app/scripts/admin.js
  line 109  col 25  ['hydraDoc'] is better written in dot notation.
  line 110  col 49  ['hydraDoc'] is better written in dot notation.
  line 162  col 22  Don't make functions within a loop.
  line 7    col 9   'jsonld' is not defined.
  line 31   col 10  'fetchHydraDoc' is defined but never used.

  ‼  5 warnings

Warning: Task "jshint:all" failed. Use --force to continue.

Aborted due to warnings.


Execution Time (2016-01-06 08:28:52 UTC)
loading tasks                 217ms  ███████████████████████████ 37%
loading grunt-newer            18ms  ███ 3%
newer:jshint:all               13ms  ██ 2%
loading grunt-contrib-jshint  174ms  ██████████████████████ 30%
jshint:all                    161ms  ████████████████████ 28%
Total 584ms

Any idea ?

Will there be future support for HATEOAS?

It is not necessarily an issue, but more something to discuss about.
Will there be any support for HATEOAS in the future? Or is there already a way to implement this in the api-platform project?

`docker-compose build` failed

When I run docker-compose build, I have this error :

[...]
  [Doctrine\DBAL\Exception\ConnectionException]                                
  An exception occured in driver: SQLSTATE[HY000] [2002] Connection timed out  



  [Doctrine\DBAL\Driver\PDOException]          
  SQLSTATE[HY000] [2002] Connection timed out  



  [PDOException]                               
  SQLSTATE[HY000] [2002] Connection timed out  


ERROR: Service 'web' failed to build: The command '/bin/sh -c ((rm -rf var/cache/* && rm -rf var/logs/* && rm -rf var/sessions/*) || true)     && composer install -o && bin/console cache:warmup -e=prod     && chown -R www-data . var/cache var/logs var/sessions' returned a non-zero code: 1

Maybe a configuration problem?

Hello @dunglas

Here is my schema.yml file:

rdfa:
  - https://raw.githubusercontent.com/schemaorg/schemaorg/sdo-gozer/data/schema.rdfa
annotationGenerators:
    - ApiPlatform\SchemaGenerator\AnnotationGenerator\PhpDocAnnotationGenerator
    - ApiPlatform\SchemaGenerator\AnnotationGenerator\DoctrineOrmAnnotationGenerator
    - ApiPlatform\SchemaGenerator\AnnotationGenerator\ConstraintAnnotationGenerator
    - ApiPlatform\SchemaGenerator\AnnotationGenerator\DunglasApiAnnotationGenerator
namespaces:
  entity: AppBundle\Entity
types:
  Thing:
    properties:
      name: ~
      description: ~
  Action:
    properties:
      url: ~
  OrganizeAction:
    properties: {}
  BookmarkAction:
    properties:
      agent:
        range: Person
        cardinality: (*..1)
  Person:
    properties: {}
  Organization:
    properties:
      url: ~

And here is the error message I get on the index page of the api:

Unable to generate an IRI for "BookmarkAction".

Do you have a hint or something to help me on this? Thanks for your help.

Question : How to deal with external resources ? (Using URL as URI ?)

I use API Platform since a year now, and I have a problem to solve about external resource and I request opinion of the API Platform community to deal with it.

The case : My API use external resources provided by other APIs

Example : A Comment API for Movies.
szkeduxyg1mwykmlfpaxmzw

I think the usage of JSON-LD help us to deal with this kind of resources.
Instead having internal resources like : "/movies/1" we use the full url resources like "http://api.imdb.com/movies/1" or "http://api.allocine.fr/films/one". So we can use URL as URI for our POST/PUT/GET requests.

Questions

  • In the API return, if we are using external resources we must have the full URL right ?
  • How to store a link with an External resource in database ? A string ? What's your opinion about performance, etc ... ?
  • How to deal with Doctrine entities ? Its kind of relation but through an API ...
  • Have you some experience with this kind of thing to share with me ?

Thanks for your returns !

Quelques informations

Sorry for english readers.

Bonjour Dunglas, j'avais quelques questions par rapport au bundle que tu propose.

  • A quand la version de Symfony en 2.8LTS ?
  • Tu dis présenter une solution angularjs complète incluse dans ton repo, mais mis à part une config de RestAngular sur la doc, je ne vois nul lien avec la partie Symfony ni exemple concret pour mettre en place cette solution.
  • J'ai actuellement un projet Symfony en 2.8 fonctionnel avec les bundles FOSUser, FOSRest, FOSOAuth et NelmioApiDoc d'installés et j'ai pas mal de difficultés à appréhender la partie OAuth. Tout est fonctionnel côté Symfony, mais côté angular, j'arrive par l'intermédiaire de hello.js ( http://gonzalo123.com/2015/03/02/building-a-angularjs-provider-for-hello-js-library/ ) à générer des tokens et accéder à mes quelques ressources Symfony mais pas d'exemples sur comment afficher nos entités avec un CRUD côté angular ou si on veut se servir de vues côté angular pour les pages de login / logout / profil / inscription / etc... et que toutes les informations d'un utilisateur en particulier soit récupéré en json côté Symfony (avec utilisation de OAuth).
    Malheureusement, outre le faite que tu spécifie pour APIDoc que ce soit simple d'utiliser OAuth, de le mettre en place, et de l'utiliser avec Angular, tu donne très peu de détails, aucun exemple, et il est dur de se dire que c'est une fonction apportée par APIDoc lorsque rien d'autres que quelques lignes de présentation sont exposées. Du coup est-ce normal? Y'a t'il des choses qui seront à venir à ce sujet ?

Voilà, je nourris quelques espoirs d'avoir trouvé ton travail sur le sujet Symfony / API Rest / Angular & OAuth et j'espère qu'il y aura une suite concrète (surtout concernant les exemples Angular et OAuth).

How can i translate the entities without to custom the controller?

Hi Everyone,
Thank you for your work shot. I have a preoccupation about API Platform.

I'm using API Platform 1.0 for one of my projects. I need to translate some fields of my entities in some languages into the API.

I will want to know:
Is it possible to make these translations without to custom the controller? if so, how can i do it? otherwise what solutions you offered me?

Thank you in advance.

Update the package

I'm a bit confused. I have installed api-platform via composer with the command "composer create-project api-platform/api-platform my-api".

Now I want to update to version 1.1 of the core via composer.

Can you explane me how?

How can I add some fields to exposed recourse ?

Hi everyone,
We have User resource.
We also have tables ("custom_attributes" and "user_custom_attributes"). In "custom_attributes" we declare fields, and in "user_custom_attributes" we have attr_id, user_id, value.
The "custom_attributes" is always different and I think it is too complicated to treat those user custom user attributes as separate recourse (because in fact they are not separate entities, it is just a way to make it flexible).

So what I want to is send such json:

{
"first_name": "Ihor",
"email" : "[email protected]"
"custom_attributes" : {
"age" : 26,
"another_key" : "another_value"
}
}

And another way around, when somebody is trying to make GET request, the result should be in the same way.

I guess I need to implement custom Normalizer.
I would really appreciate any tips. Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.