Git Product home page Git Product logo

api-platform / create-client Goto Github PK

View Code? Open in Web Editor NEW
364.0 25.0 128.0 1.76 MB

Generate React or Vue.js-based Progressive Web Apps from an Hydra-enabled API. Also support React Native.

Home Page: https://api-platform.com/docs/client-generator/

License: MIT License

JavaScript 25.94% TypeScript 40.04% Vue 33.06% Shell 0.94% CSS 0.02%
react react-native reactjs redux vue vuejs typescript generator hydra hydra-api

create-client'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.

create-client's People

Contributors

alanpoulain avatar aloneh avatar artandor avatar bolid1 avatar dependabot-preview[bot] avatar dependabot[bot] avatar devel-pa avatar dunglas avatar electricbonfire avatar fabious avatar gregcop1 avatar jamesgeorge007 avatar jmontoyaa avatar justinezahiri avatar kuznetsovsite avatar luca-nardelli avatar malikalahfaoui avatar matyo91 avatar mbrodala avatar meyerbaptiste avatar mysiar avatar pierre-h avatar potik1 avatar sebheitzmann avatar sh41 avatar shywim avatar soyuka avatar toofff avatar valentincrochemore avatar weaverryan 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

create-client's Issues

Wrong links to nested entities

Wrong routes gnerated for nested entities
generated https://api-front.geomysiar.pl/2/show/%2Fbooks%2F2
instead https://api-front.geomysiar.pl/reviews/show/%2Fbooks%2F2

[VueJS] Wrong payload name for mutations

There is a mistake in file update.js.

state.updateLoading = payload.loading;

should be

state.updateLoading = payload.updateLoading;

Without that, when I watch for updateLoading: function (loading) { // some code }, loading is undefined

Discuss and vote for new features ✅

This project is great 🔥 But if it will be somehow extensible (through plugin system for example) it will became more popular.

For example

npx generate-api-platform-client http://my-api.com src --generator=react --view-plugins=react-jsonschema-form --state-plugins=react-mobx

So, instead redux-form and plain html markup we can use

Insteat redux itself:

  • mobx over 17k⭐️, over 100k weekly installs
  • and others (mobx-state-tree ~4k⭐️, over 8k install), easy-peasy - new react's hooks based implementation of redux

Please, vote for some of above or post you opinion 🙌

TypeError: Cannot read property 'properties' of undefined

Hi, I am trying to generate a react client from a swagger API.

npx @api-platform/client-generator http:/myapi/swagger/docs/v1 src/ --resource Item --format swagger

I get the error

TypeError: Cannot read property 'properties' of undefined

I stepped through this a little and this error occurs here:

exports.default = function (response, entrypointUrl) {
  var paths = (0, _lodash.uniq)((0, _keys2.default)(response.paths).map(function (item) {
    return item.replace("/{id}", "");
  }));

  var resources = paths.map(function (item) {
    var name = item.replace("/", "");
    var url = removeTrailingSlash(entrypointUrl) + item;
    var firstMethod = (0, _keys2.default)(response.paths[item])[0];
    var title = response.paths[item][firstMethod]["tags"][0];
    /* 
     * ERROR OCCURS HERE:
     */
    var fieldNames = (0, _keys2.default)(response.definitions[title].properties);

What happens, is it attempts to get fieldNames from

var title = response.paths[item][firstMethod]["tags"][0]; // tags[0] = "Item"
response.definitions["Item"].properties.

However, the Item endpoint does not return an Item object, it returns "ApiResponse[ItemDto]".

"paths": {

    "/api/v1/Item": {
      "get": {
        "tags": [
          "Item"
        ],
        ....
        "parameters": [
	....
        ],

        "responses": {
          "200": {
            "description": "OK",
            "schema": {
              "$ref": "#/definitions/ApiResponse[ItemDto]"
            }
          }
        }
      },
},
"definitions": {
"ApiResponse[ItemDto]": {
      "type": "object",
      "properties": {
        "Pagination": {
          "$ref": "#/definitions/ApiPagination"
        },
        "Data": {
          "type": "array",
          "items": {
            "$ref": "#/definitions/ItemDto"
          }
        }
      }
    },

So I can see that to find the properties it needs to traverse the "$ref's".

Any advice would be appreciated.

Calling wrong api end point

HI

I had a symfony app, so I added APIResource on entity. Now I API's are working perfectly. But Client generated app for react is always calling wrong API.
For example:
If I have a resource faq. It is supposed to call http://localhost:8000/api/faqs but it's calling http://localhost:8000/faqs.

In my entrypoint.js I have Base URL as http://localhost:8000/api

What's getting wrong there?

Thanks

Client-Generator error lodash from container personnal

Hello, everybody,

I had a problem with the client generator of Api-platform.
I explain my problem, i don't use the container propose by "Api platform".
I had create two containers (Symfony and React).
Api Platform work very well.
But when i create the view with "npx @api-platform/client-generator" this error appear :
"npx: installed 284 in 11.132s
Cannot find module 'lodash'"
What resolve this problem ?

Unable to find the URL for entrypoint

I have a resource that collection operation is empty:

* @ApiResource(
 *     attributes={"pagination_enabled"=false},
 *     collectionOperations={},
 *     itemOperations={"get"}
 * )

when i want to generate client code, it fail and can not generate anythings for this & other resource:

Error: Unable to find the URL for "http://my.local/api/docs.jsonld#Entrypoint/county".
    at fetchEntrypointAndDocs.then.response (/usr/local/share/.config/yarn/global/node_modules/@api-platform/api-doc-parser/lib/hydra/parseHydraDocumentation.js:433:17)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)

[IDEA] Add custom generator support

Hello,

It would be great to add an option to support custom generator with custom templates.

For example : I often use Semantic UI for React in TypeScript in multiples projects. So I'd like to create my own generator with all templates needed and to use it like this generate-api-platform-client --generator=reactSemanticTs.

I don't know what's the best way to support this (specifically how to not overwrite custom generators when updating the client-generator). Does someone have an idea ?

Thank you for your great work !

[VueJS] Missing violations state on store

Hello,

Thanks for this awesome project.

I think the property violations is missing on the generated create.js module.

I noticed that when I submit a create form, errors are displayed on top of the form and not after each fields.

Without violations state
image

With violations state
image

I just had to change create.js

const state = {
  loading: false,
  error: '',
  created: null
};

to

const state = {
  loading: false,
  error: '',
  created: null,
  violations: null
};

Incorrect path generated for calls to API

Reproduction steps:
Install as per README.
run

$ api-platform-generate-crud https://demo.api-platform.com/ src/
$ grep -ri -E "Fetch\('" src/

Result:

src/actions/book/create.js:    return bookFetch('/ooks', {method: 'POST', body: JSON.stringify(values)})
src/actions/book/list.js:    bookFetch('/ooks')
src/actions/review/create.js:    return reviewFetch('/eviews', {method: 'POST', body: JSON.stringify(values)})
src/actions/review/list.js:    reviewFetch('/eviews')

Expected result:

src/actions/book/create.js:    return bookFetch('/books', {method: 'POST', body: JSON.stringify(values)})
src/actions/book/list.js:    bookFetch('/books')
src/actions/review/create.js:    return reviewFetch('/reviews', {method: 'POST', body: JSON.stringify(values)})
src/actions/review/list.js:    reviewFetch('/reviews')

When the react-app is run a message of Unexpected token < in JSON at position 0 appears on the list page and on submission of a create form.

This can be manually fixed by correcting the strings in the relevant create.js and list.js files.

Resources' routes components are not displayed

Hi,
I followed the doc to generate a react client :

  • create React react app and install composants using yarn.
  • add the bootstrap css link
  • generate the files for all the resources (book and review) of my local API (based on api-platform tutorial)
  • register the reducers and components in the index.js as the give example (see the code below)

But result displays only the <h1>Not found</h1> without the book and review routes.

Did I make a mistake ? Did I misunderstand something with the client generator or React itself (I have basic notions but I'm not an expert)

Thank you for your help.

index.js code :
import React from 'react';
import ReactDom from 'react-dom';
import { createStore, combineReducers, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { reducer as form } from 'redux-form';
import { Router, Route, Switch } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import { syncHistoryWithStore, routerReducer as routing } from 'react-router-redux'
import registerServiceWorker from './registerServiceWorker';

// import reducers
import book from './reducers/book/';
import review from './reducers/review/';

//import routes
import bookRoutes from './routes/book';
import reviewRoutes from './routes/review';

const store = createStore(
combineReducers({routing, form, book, review}), // Don't forget to register the reducers here
applyMiddleware(thunk),
);

const history = syncHistoryWithStore(createBrowserHistory(), store);

ReactDom.render(
<Provider store={store}>
<Router history={history}>
<Switch>
{ bookRoutes }
{ reviewRoutes }
<Route render={() => <h1>Not Found</h1>}/>
</Switch>
</Router>
</Provider>,
document.getElementById('root')
);
registerServiceWorker();

[Vuejs] Documentation to import modules should not use brace bracket

When generating a module for VueJs, the generated documentation shows

// Add the modules in the store
import { article } from './store/modules/article/';

export const store = new Vuex.Store({
  // ...
  modules: {
    article
  }
});

However the ./store/modules/article/index.js has an export default {}
so the code should be
import article from './store/modules/article/';

[VUEJS] - [vuex] unknown action type and getter type

When the Entity of API (PHP Class) is "Book", the client generator for vue.js works and the interface is working too.

But when I change "Book" Entity for other name ("Boo", "Booka", ...), the client generator still working, but the interface is bugging.

I got errors in the store (vuex) :
[vuex] unknown action type: boo/list/getItems
[vuex] unknown getter: boo/list/loading
[vuex] unknown getter: boo/del/deleted
[vuex] unknown getter: boo/list/error
[vuex] unknown getter: boo/list/view
[vuex] unknown getter: boo/list/items

But the action and getters exist so I don't understand the error.

api_platform_client_bug_vuejs_store

Vue project - ENTRYPOINT is undefined

Hello,

I'm trying to use api platform from a SF flex installation.
It's working great but I've an issue with the client side in Vue.

My issue is related to the API endpoint. I don't have the api suffix.

I see a import { ENTRYPOINT } from '../config/entrypoint'; in the src/utils/fetch.js but this is not working.

Do I miss something or the code is broken?

How might I handle authentication

Hi there,

Just started playing with the generator (for React.js), and think it's pretty awesome.

My current problem is that my API is protected using JWT.

Can you advise how I might be able to add log in functionality? I'm pretty new to React.js.

What is the roadmap of this project?

I asked this question on the admin component issues, but it sure fits better here.

The project description says: "Generate a CRUD application built with React, Redux and React Router from an Hydra-enabled API", but I see you already have a Vue generator in place and React Native and Admin on Rest also in progress.

So, I could not tell if your main goal is to have a lot of simple generators or maybe to have a very robust one (or very robust ones).

Please, I also want to know what are your objectives specially with the react and react native generators. I see that, for instance, the admin on rest use sagas, but you use thunks. Do you have a desired architecture and functionality list to be supported by the generator?

I hope that we can help you with this project, because I like it and it seems very promising.

Error when I try to generate the VueJs Admin

Hello,

I Try to use the VueJs generator. But no success for the moment.

I have this

$ generate-api-platform-client -g vue http://api-intranet:8888/web/app_dev.php/ src/ --resource TypeDiplome

{ api: 
   Api {
     entrypoint: 'http://api-intranet:8888/web/app_dev.php',
     resources: [] },
  response: 
   Body {
     url: 'http://api-intranet:8888/web/app_dev.php',
     status: 500,
     statusText: 'Internal Server Error',
     headers: Headers { _headers: [Object] },
     ok: false,
     body: 
      PassThrough {
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 7,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        _transformState: [Object] },
     bodyUsed: false,
     size: 0,
     timeout: 0,
     _raw: [],
     _abort: false },
  status: 500 }

This link http://api-intranet:8888/web/app_dev.php works well in browser.
I Have already use this generator with success...

I don't understand what I forget ?

Thanks

Can I add handlebars helpers to my custom template?

I'm developing a custom template for Vue using Vuetify instead of Bootstrap. But I have a problem.

The original Form.vue template, renders all input types the same way:

{{#each formFields}}
    <input ... type="{{{ type }}}" ...>
    ...
{{/each}}

But Vuetify uses directives for de different types so I need to use a compare helper like this:

{{#each formFields}}
    {{#compare type "==" "checkbox"}}
        <v-checkbox ... >
    {{/compare}}
    {{#compare type "==" "text" }}
        <v-ext-field ... >
    {{/compare}}
    ...
{{/each}}

But I haven't compare helper available

Error: Missing helper: "compare"

The "if" helper only works for one variable.

AdminOnRestGenerator.js have import hbh_comparison from 'handlebars-helpers/lib/comparison' but others one deos not.

How to make it work with swagger.io petstore example.

My team does not (yet) use api-platform as I have to build an mvp showcasing whats possible using their legacy swagger system.

I have .json files with the documentation, can they be used to generate the app aswell?

Thanks in Advance

Add Angular generator

Add Angular generator to API-Platform client-generator.
With React, Vue.js and shortly coming React Native this could be the most comprehensive front app support for API-Platform

Allow providing custom templates

This tool is very useful but it can be very useful to allow passing a path for custom scaffolding templates, and fallback to the default one if not set.

TypeError: Cannot read property 'status' of undefined on generating frontend code

Hallo I'm trying to get the client code generator running:

I have an api which returns something like this:

christophs-mbp:test htz$ curl http://handicap-berechnen.lo/api
{"@context":"\/api\/contexts\/Entrypoint","@id":"\/api","@type":"Entrypoint","club":"\/api\/clubs","course":"\/api\/courses","teeBox":"\/api\/tee_boxes"}

but running the generator results in an error:

christophs-mbp:test htz$ generate-api-platform-client http://handicap-berechnen.lo/api src
TypeError: Cannot read property 'status' of undefined
    at /Users/christophhautzinger/.config/yarn/global/node_modules/@api-platform/api-doc-parser/lib/hydra/parseHydraDocumentation.js:295:134
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:160:7)

the same error as on any non existant api endpoint url:

calling the demo code works:

christophs-mbp:test htz$ generate-api-platform-client https://demo.api-platform.com src/
Code for the "Review" resource type has been generated!
Paste the following definitions in your application configuration:

// import reducers
import review from './reducers/review/';

//import routes
import reviewRoutes from './routes/review';

// Add the reducer
combineReducers(review,{/* ... */}),

// Add routes to <Switch>
{ reviewRoutes }

Code for the "Book" resource type has been generated!
Paste the following definitions in your application configuration:

// import reducers
import book from './reducers/book/';

//import routes
import bookRoutes from './routes/book';

// Add the reducer
combineReducers(book,{/* ... */}),

// Add routes to <Switch>
{ bookRoutes }

my node version is

christophs-mbp:test htz$ node -v
v9.3.0

Do i need some special kind of configuration? didn't get it from the docs.

React native: display the id

For parity with the React generator, I think we should display the ID by default (up to the developper to remove it if needed)

React client files changes doesn't work without restarting Docker container

Hi!

First of all, thanks a lot for your awesome work with API Platform! :)

I have a problem with the React client:

After generating the client with this command (from website tutorial): docker-compose exec client generate-api-platform-client (no problem all files are generated and no error message), I edited the client/src/index.js as it's mentioned in the doc but when I add modifications, save the file, and reload the page (https://localhost/books/), "Not Found" is displayed.
Same thing when I edit client/src/Welcome.js file (add two exclamation points for example): nothing change.
I have to stop the client container, and restart it to see my changes :/

Do you see where is the problem?

I'm on Windows 10 with Docker for Windows (latest version).

Don't hesitate to ask me further information!

Thanks ;)

attribute must be "float", "string" given.

bonjour, j'utilise vuejs CLIENT GENERATOR COMPONENT ,
j’essaye de crée un nouveau enregistrement a partir de l'interface

que dois je faire pour résoudre ce problème ?

version to 0.1.12

Hi

It would be very cool if the recent changes related to VUE were already tagged (I'm starting my adventure with this generator)

Swagger not works

Run

generate-api-platform-client https://demo.api-platform.com/ output/ --resource Book --format swagger

We have error

TypeError: Cannot read property 'title' of undefined at Yarn\Data\global\node_modules@api-platform \api-doc-parser\lib\swagger\parseSwaggerDocumentation.js:28:31 at process._tickCallback (internal/process/next_tick.js:68:7)
--

Using axios lib instead of fetch()

What about using Axios ? It provides a good API to make HTTP requests and can be used to simplify things like pagination.

For example, to get the second page of my Book resource :

axios.get('/books', {
    params: {
      page: 2
    }
  })
  .then(function (response) {
    // ...
  })
  .catch(function (error) {
    // ...
  });

With fetch() we don't have this flexibility and we need to provide the full url each time.

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.