# GraphQL Mutation Crash Course

{% hint style="info" %}
The GraphQL API is an additional feature. If you would like to add the GraphQL Api to your Fast Weigh subscription, contact us at *865-219-2980* or <support@tacinsight.com>.
{% endhint %}

If you are used to using a REST API POST or PUT request to update data via an API, using GraphQL "mutations" may seem like a big change. However, a lot of the fundamentals are similar under-the-hood. While you will be using a single endpoint for every "mutation", the payloads will be familiar and everything will be "strongly typed" to help prevent errors.

## GraphQL Mutation Basics

With GraphQL, you're still issuing a request to an HTTP endpoint just like you would for a REST API. The big difference is that **there is a single endpoint that services all requests**.

For Fast-Weigh, the endpoint looks like this:

```
https://graphql.fast-weigh.com/
```

## **Writing Your First Mutation**

{% hint style="info" %}
Before you get started, make sure to read the previous articles covering the intial set up!

[Authentication](/fast-weigh-knowledge-base/references/api-documentation/graphql-v2-api/authentication.md)

[Tooling](/fast-weigh-knowledge-base/references/api-documentation/graphql-v2-api/tooling.md)
{% endhint %}

Here's a simple mutation that adds a new Customer:

```graphql
mutation AddCustomer {
  createCustomer(
    customers: [
      {
        customerID: "New"
        customerName: "New Customer!"
        billingModeCode: "A"
        termsCode: "1"
        creditStatus: O
        allowedPaymentMethods: NONE
        requireOrder: true
        ticketPORule: DEFAULT_ONLY
        taxCode: "NON"
      }
    ]
  ) {
    savedItems {
      customerKey
      customerID
      customerName
    }
    errors {
      message
    }
    success
  }
}

```

Let's break that syntax into its parts:

```graphql
<OperationType> <MutationName> {
  <MutationOperation>(<MutationInput>) {
    <ResponseQuery>
  }
}
```

### **The Mutation Syntax**

#### **Operation Type**

This is the specifier for **what you want to do with the GraphQL API**.&#x20;

If you are familiar with REST APIs, you can think of this as the "HTTP Method" (PUT, POST, GET, etc). If you are familiar with SQL, you can think of this as the "SQL Command" (SELECT, INSERT, UPDATE, etc)

**GraphQL endpoints support the following Operations:**

* **query**: ✅ Similar to a SQL `SELECT` statement
* **mutation**: ✅ Similar to a SQL `UPDATE` or `INSERT` statement (You are here!)
* **subscription**: ❌ A WebSocket-based live data stream

{% hint style="info" %}
Note that Fast-Weigh does not support the `subscription` type at this time.
{% endhint %}

#### Mutation Name

This is the identifier for the mutation. **You can give it any name you'd like**.&#x20;

In the "AddCustomer" example, the Mutation Name could have been "addNewCustomer", "add-customer", or anything else you could dream up. I went with "AddCustomer" for brevity.

#### Mutation Operation

This is the name of the specific operation you want to perform. Each mutation operation requires and "input" and, optionally, a response query body.&#x20;

If you are familiar with REST APIs, you can think of this as similar to the specific endpoint you are calling. If you are familiar with SQL, you can think of this as the SQL operation that you are performing (UPDATE, DELETE, etc).

#### Mutation Input

This is the input for the new data you are sending with the mutation. In the AddCustomer example, this is all of the required (and optional) fields for creating a new customer.

If you are familiar with REST APIs, you can think of this as the parameters for the endpoint. If you are familiar with SQL, you can think of this as the table and columns you are performing an action on.

#### Response Query

This is (normally) an optional query that provides the response to the mutation. Generally, it is recommended to include a Response Query so that you can see if the request was successful, if there were any errors, what was changed, etc.

### The Mutation Response

The response back from this query will be a JSON response matching the format of the response query body.

```json
{
  "data": {
    "createCustomer": {
      "savedItems": [
        {
          "customerKey": 1,
          "customerID": "New",
          "customerName": "New Customer!"
        }
      ],
      "errors": [],
      "success": true
    }
  }
}
```

### &#x20;Checking the Mutation Input Format

The GraphQL schema includes the desired input format for the mutation. For most operations, the input will be a complex object matching the Type that the mutation is changing.

{% hint style="info" %}
Check out our [GraphQL Schema](/fast-weigh-knowledge-base/references/api-documentation/graphql-v2-api/graphql-schema.md) article for more information about viewing the schema.
{% endhint %}

If you are adding a new record, you will want to leave the "primary key" unset, and the operation will auto-assign a new key for the record (IE CustomerKey is the primary key for Customer).&#x20;

If you are updating an existing record, you will need to include the "primary key" so the operation knows which record to update. You can sometimes skip the "primary key" and rely on a "primary identifier" to match the record (IE CustomerID instead of CustomerKey), but it is generally best practice to use the "primary key" instead.

### Compound Mutations

Completely separate requests can also be **merged within a single mutation**. This is not a very common usage pattern, since most of the time you are running more than one mutation, it would be to add multiple records of the same type. Instead of calling the mutation multiple times, you would just pass more than one record to the "Mutation Input".

{% hint style="info" %}
Typically, compound mutations would only be used to stitch together bulk-adding or updating smaller Types. You would not want to combine multiple large payload mutations in the same request/response as this can be quite taxing due to complexity and payload size.
{% endhint %}

Here's an example request for adding a couple of resources within Fast-Weigh.

```graphql
mutation AddYardAndTruck {
  createYard(yards: [{ yardName: "NEW", yardDescription: "New Yard!", locationKey: 1 }]) {
    savedItems {
      yardKey
      yardName
      yardDescription
    }
    errors {
      message
    }
    success
  }
  createTruck(
    trucks: [
      {
        truckID: "New"
        active: true
        defaultHaulerKey: 1
        tareWeight: 5
        hasSMS: false
        ticketNotification: false
        enableDispatching: false
        allHauler: false
      }
    ]
  ) {
    savedItems {
      truckKey
      truckID
      defaultHaulerID
    }
    errors {
      message
    }
    success
  }
}
```

Results in:

```json
{
  "data": {
    "createYard": {
      "savedItems": [
        {
          "yardKey": 1,
          "yardName": "NEW",
          "yardDescription": "New Yard!"
        }
      ],
      "errors": [],
      "success": true
    },
    "createTruck": {
      "savedItems": [
        {
          "truckKey": 1,
          "truckID": "New",
          "defaultHaulerKey": 1
        }
      ],
      "errors": [],
      "success": true
    }
  }
}
```

```json
{
  "data": {
    "yards": [
      {
        "yardName": "BAUM",
        "yardDescription": "Primary Pit",
        "location": {
          "locationName": "ROCK",
          "locationDescription": "Rockland Quarry",
          "region": {
            "regionName": "TN",
            "regionDescription": "Tennessee"
          }
        }
      },
      {
        "yardName": "AGG",
        "yardDescription": "Second Pit",
        "location": {
          "locationName": "ROCK",
          "locationDescription": "Rockland Quarry",
          "region": {
            "regionName": "TN",
            "regionDescription": "Tennessee"
          }
        }
      }
    ],
    "taxCodes": [
      {
        "code": "TN925",
        "materialPercent": 0.0925,
        "freightPercent": 0.0925,
        "surchargePercent": 0.0925
      },
      {
        "code": "EXEMPT",
        "materialPercent": 0,
        "freightPercent": 0,
        "surchargePercent": 0
      }
    ],
    "products": [
      {
        "productID": "101",
        "productDescription": "1/4 Pea Gravel"
      },
      {
        "productID": "102",
        "productDescription": "3/8 Pea Gravel"
      },
      {
        "productID": "103",
        "productDescription": "1/2 Pea Gravel"
      }
    ]
  }
}
```

### Using Parameters for the Input <a href="#using_parameters" id="using_parameters"></a>

Parameters allow you to pass data into your GraphQL statement from outside of the mutation body.

You can define one or more parameters by adding them to the *very top of the query* by the Query Name. Here is our original Query Syntax example, with a parameter added:

```graphql
<OperationType> <MutationName> ($<ParameterName>: <ParameterType>) {
 <MutationOperation>(<MutationInput>: <ParameterName>) {
    <ResponseQuery>
  }
}
```

{% hint style="info" %}
Note the `$` in front of the parameter name! This character is what tells GraphQL that something is a parameter, and it is required at the beginning of the parameter name.
{% endhint %}

#### Common parameter input usage <a href="#common_parameter_types" id="common_parameter_types"></a>

There are a few ways that you can use parameters in the mutation.&#x20;

The first way is to pass the *entire* *input* into the query as a parameter. This can give you more control over the data, but if you have any values that are *always the same*, you will have to define them each time you build the parameter. This is also going to be the only way you can pass *different* information to multiple records via a parameter.

Here is an example of our AddCustomer mutation, but using a parameter for the entire input, instead of hard-coding it in.

**Query:**

```graphql
mutation AddCustomer($input: [APICreateCustomerModelInput]) {
  createCustomer(customers: $input) {
    savedItems {
      customerKey
      customerID
      customerName
    }
    errors {
      message
    }
    success
  }
}

```

**GraphQL Variables**

```json
{
  "input": [{
        "customerID": "New",
        "customerName": "New Customer!",
        "billingModeCode": "A",
        "termsCode": "1",
        "creditStatus": "O",
        "allowedPaymentMethods": "NONE",
        "requireOrder": true,
        "ticketPORule": "DEFAULT_ONLY",
        "taxCode": "NON"
      }]
}
```

You can also pass individual input fields as parameters into the mutation. If you only need to set a handful of fields for a single record, then this can be more efficient than passing the entire payload. Additionally, you coiuld use a single field parameter to pass the same value(s) to multiple records' fields at once.

Here is an example of our AddCustomer mutation with multiple input parameters for a single record.

**Query:**

```graphql
mutation AddCustomer($customerID: String!, $customerName: String!) {
  createCustomer(
    customers: [
      {
        customerID: $customerID
        customerName: $customerName
        billingModeCode: "A"
        termsCode: "1"
        creditStatus: O
        allowedPaymentMethods: NONE
        requireOrder: true
        ticketPORule: DEFAULT_ONLY
        taxCode: "NON"
      }
    ]
  ) {
    savedItems {
      customerKey
      customerID
      customerName
    }
    errors {
      message
    }
    success
  }
}

```

**GraphQL Variables**

```json
{
 "customerID": "New",
 "customerName": "New Customer!"
}
```

### **Putting Mutations Into Practice**

Once you've got the mutation basics down, it's time to start experimenting and using them for your own use case or start running mutations via HTTP and code in your programming language of choice.

[GraphQL for Developers](/fast-weigh-knowledge-base/references/api-documentation/graphql-v2-api/graphql-for-developers.md)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://help.tacinsight.com/fast-weigh-knowledge-base/references/api-documentation/graphql-v2-api/graphql-mutation-crash-course.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
