Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Json Schema Laravel Package

api-platform/json-schema

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require api-platform/json-schema
    

    Register the service provider in config/app.php (if not auto-discovered):

    'providers' => [
        // ...
        ApiPlatform\JsonSchema\JsonSchemaServiceProvider::class,
    ],
    
  2. Basic Usage Generate a JSON Schema from a PHP class (e.g., an Eloquent model or DTO):

    use ApiPlatform\JsonSchema\JsonSchemaGenerator;
    
    $generator = app(JsonSchemaGenerator::class);
    $schema = $generator->generateSchema(new YourClass());
    
  3. First Use Case Use the schema to validate incoming API requests or document your API:

    $schemaJson = json_encode($schema, JSON_PRETTY_PRINT);
    file_put_contents('schema.json', $schemaJson);
    

Implementation Patterns

Workflows

  1. Schema Generation for Models Integrate with API Platform or standalone:

    $userSchema = $generator->generateSchema(new User());
    
  2. Dynamic Schema Generation Generate schemas dynamically in controllers or middleware:

    public function showSchema(Request $request)
    {
        $schema = $this->jsonSchemaGenerator->generateSchema(new YourModel());
        return response()->json($schema);
    }
    
  3. Validation Integration Use the schema with a validator (e.g., Symfony Validator or JSON Schema validators like justinrainbow/json-schema):

    $validator = new \Symfony\Component\Validator\Validator\ValidatorBuilder();
    $validator = $validator->getValidator();
    $errors = $validator->validate($data, $constraintsFromSchema($schema));
    
  4. API Documentation Embed schemas in OpenAPI/Swagger docs (e.g., via nelmio/api-doc-bundle):

    # config/packages/nelmio_api_doc.yaml
    swagger:
        schemas:
            User: !php/const ApiPlatform\JsonSchema\JsonSchemaGenerator::class
    

Integration Tips

  • Leverage API Platform: If using API Platform, combine with api-platform/core for seamless schema generation from entities.
  • Caching: Cache generated schemas to avoid regeneration:
    $cacheKey = 'schema_' . md5(get_class($object));
    $schema = cache()->remember($cacheKey, now()->addHours(1), function () use ($generator, $object) {
        return $generator->generateSchema($object);
    });
    
  • Custom Context: Pass context to control schema generation (e.g., exclude properties):
    $schema = $generator->generateSchema($object, [
        'exclude' => ['password', 'createdAt'],
    ]);
    

Gotchas and Tips

Pitfalls

  1. Circular References Avoid infinite loops with recursive relationships:

    // May cause issues if not handled
    $generator->generateSchema(new User()); // User hasMany Posts, Post belongsTo User
    

    Fix: Use context to limit depth or break cycles manually.

  2. Type Mismatches The generator may not infer complex types (e.g., custom collections) accurately. Override with annotations or metadata:

    /**
     * @JsonSchema(type="array", items={"type": "string"})
     */
    public function getTags(): array { ... }
    
  3. Performance Generating schemas for large objects (e.g., deeply nested graphs) can be slow. Cache aggressively or lazy-load.

  4. API Platform Quirks If using API Platform, ensure your entity has proper ApiResource configuration. The generator respects serializationContext and denormalizationContext.

Debugging

  • Inspect Generated Schema: Use json_encode($schema, JSON_PRETTY_PRINT) to debug structure.
  • Check for Missing Properties: Ensure all properties are public or have getters/setters (private properties are ignored by default).
  • Validate Against Known Schemas: Use tools like JSON Schema Validator to test generated schemas.

Extension Points

  1. Custom Schema Generators Extend ApiPlatform\JsonSchema\Generator\GeneratorInterface for custom logic:

    class CustomGenerator implements GeneratorInterface {
        public function generateSchema($object, array $context = []): array {
            // Custom logic
        }
    }
    

    Register it in the container:

    $this->app->bind(JsonSchemaGenerator::class, function () {
        return new CustomGenerator();
    });
    
  2. Modify Default Behavior Override the default generator in config/services.php:

    'api_platform.json_schema' => [
        'generator' => App\CustomGenerator::class,
    ],
    
  3. Add Metadata Use annotations or attributes to customize schema generation:

    use ApiPlatform\JsonSchema\Annotation\JsonSchema;
    
    class User {
        /**
         * @JsonSchema(type="string", format="date-time")
         */
        public $createdAt;
    }
    
  4. Handle Complex Types For custom types (e.g., UUIDs, enums), register type handlers:

    $generator->addTypeHandler('uuid', function () {
        return ['type' => 'string', 'format' => 'uuid'];
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
aimeos/prisma
besmartand-pro/php-quality-config
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views