GraphQL Cookbook

Creating an object through the Parse GraphQL API

Problem

You want to create a new object in your database through the Parse GraphQL API.

Solution

Using the parse GraphQL, there are two different ways to create a new object in your database:

  • Using generic mutation - this is the mutation that you must use if you do not have already created your object’s class.
  • Using class mutation - this is the recommended mutation if you have already created your object’s class.

Using generic mutation

When you use the create generic mutation, Parse Server behaves like a schemaless database. It means that you do not need to define your object’s class in your application’s schema beforehand. You just need to send your object’s data, and Parse Server will not only store it, but also learn from it, and automatically create a new class in your application’s schema.

Therefore, the objects’ create generic mutation is the method that you must use for creating a new object if you do not have already created your object’s class. You can also use this mutation for creating an object of pre-existing classes, but, for these cases, we recommend using the class mutation.

Example:
1
2
3
4
5
6
7
8
mutation CreateObject {
  objects {
    create(className: "Hero", fields: { name: "Luke Skywalker" }) {
      objectId,
      createdAt
    }
  }
}
Result:
1
2
3
4
5
6
7
8
9
10
{
  "data": {
    "objects": {
      "create": {
        "objectId": "ffyOBOTk85",
        "createdAt": "2019-07-15T01:25:20.875Z"
      }
    }
  }
}

Using class mutation

Once you have already created your object’s class in your application’s schema (for instance, using the generic mutation), Parse Server instantly adds to your GraphQL API a new create<ClassName> mutation to create a new object of this class.

Therefore, the object’s class mutation is the recommended method for creating a new object if you have already created your object’s class. Since this mutation knows your class’ data, it will automatically make available for you additional features like code auto-complete and validation. You also don’t need to specify the data types when sending dates, pointers, relations, files, geo points, polygons, or bytes through the class create mutation.

Example:

This example will only work if you have already created your object’s class. You can create a class using the generic mutation.

1
2
3
4
5
6
7
8
mutation CreateHero {
  objects {
    createHero(fields: { name: "R2-D2" }) {
      objectId,
      createdAt
    }
  }
}
Result:
1
2
3
4
5
6
7
8
9
10
{
  "data": {
    "objects": {
      "createHero": {
        "objectId": "jJH0aQQjfs",
        "createdAt": "2019-07-15T02:22:04.982Z"
      }
    }
  }
}