### Setup Shopify API Context Source: https://shopify.github.io/shopify-api-ruby/getting_started Initialize the ShopifyAPI::Context with your application's credentials and settings. This setup is crucial for authenticating and interacting with the Shopify API. It should be called when your application starts. ```ruby ShopifyAPI::Context.setup( api_key: "", api_secret_key: "", host_name: "", scope: "read_orders,read_products,etc", is_embedded: true, # Set to true if you are building an embedded app is_private: false, # Set to true if you are building a private app api_version: "2021-01" # The version of the API you would like to use ) ``` -------------------------------- ### Install Shopify API Ruby Gem Source: https://shopify.github.io/shopify-api-ruby/getting_started Add the Shopify API gem to your project's Gemfile. This is the first step to include the Shopify API functionalities in your Ruby application. ```ruby gem "shopify_api" ``` -------------------------------- ### GET Request Example Source: https://shopify.github.io/shopify-api-ruby/usage/rest Demonstrates how to perform a GET request to fetch resources, such as products, from the Shopify Admin API. ```APIDOC ## GET /admin/api/{api_version}/products.json ### Description Fetches a list of products from the Shopify store. ### Method GET ### Endpoint `/admin/api/{api_version}/products.json` ### Parameters #### Query Parameters - **limit** (Integer) - Optional - The number of results to retrieve per page. - **page_info** (String) - Optional - Used for pagination to get the next or previous set of results. ### Request Example ```ruby # Create a new client. client = ShopifyAPI::Clients::Rest::Admin.new(session: session) # Use `client.get` to request the specified Shopify REST API endpoint, in this case `products`. response = client.get(path: "products") # Do something with the returned data some_function(response.body) ``` ### Response #### Success Response (200) - **body** (Hash) - The response body containing product data. - **code** (Integer) - The HTTP status code (e.g., 200). - **headers** (Hash) - The response headers. - **next_page_info** (String) - Information for fetching the next page of results. - **prev_page_info** (String) - Information for fetching the previous page of results. #### Response Example ```json { "products": [ { "id": 12345, "title": "Example Product", "body_html": "

This is an example product.

", "vendor": "Example Vendor", "product_type": "Example Type" } ] } ``` ``` -------------------------------- ### POST Request Example Source: https://shopify.github.io/shopify-api-ruby/usage/rest Shows how to create a new resource, like a product, by sending a POST request with a JSON body. ```APIDOC ## POST /admin/api/{api_version}/products.json ### Description Creates a new product in the Shopify store. ### Method POST ### Endpoint `/admin/api/{api_version}/products.json` ### Parameters #### Request Body - **product** (Object) - Required - An object containing the details of the product to be created. - **title** (String) - Required - The name of the product. - **body_html** (String) - Optional - The description of the product, in HTML format. - **vendor** (String) - Optional - The vendor of the product. - **product_type** (String) - Optional - The type of product. ### Request Example ```ruby # Create a new client. client = ShopifyAPI::Clients::Rest::Admin.new(session: session) # Build your post request body. body = { product: { title: "Burton Custom Freestyle 151", body_html: "\u003cstrong\u003eGood snowboard!\u003c\/strong\u003e", vendor: "Burton", product_type: "Snowboard", } } # Use `client.post` to send your request to the specified Shopify Admin REST API endpoint. # This POST request will create a new product. client.post({ path: "products", body: body, }); ``` ### Response #### Success Response (201) - **body** (Hash) - The response body containing the newly created product data. - **code** (Integer) - The HTTP status code (e.g., 201). - **headers** (Hash) - The response headers. #### Response Example ```json { "product": { "id": 98765, "title": "Burton Custom Freestyle 151", "body_html": "Good snowboard!", "vendor": "Burton", "product_type": "Snowboard" } } ``` ``` -------------------------------- ### ShopifyAPI::Clients::Rest::Admin Instantiation Source: https://shopify.github.io/shopify-api-ruby/usage/rest Provides examples of how to instantiate the `ShopifyAPI::Clients::Rest::Admin` client with different combinations of session and API version. ```APIDOC ## ShopifyAPI::Clients::Rest::Admin Instantiation ### Description This section details how to create an instance of the `ShopifyAPI::Clients::Rest::Admin` client, which is used to make requests to the Admin API. You can instantiate it with default session and API version, or specify them explicitly. ### Method Constructor ### Endpoint N/A ### Parameters #### Constructor Parameters - **session** (`ShopifyAPI::Auth::Session` | nil) - Optional - The session object to use for authentication. Defaults to `nil`, which infers the active session from `ShopifyAPI::Context.active_session`. - **api_version** (`String` | nil) - Optional - The API version to use for requests. Defaults to `nil`, which infers the version from `ShopifyAPI::Context.setup`. ### Request Example ```ruby # Create a default client using active session and configured API version client = ShopifyAPI::Clients::Rest::Admin.new # Create a client with a specific session object client = ShopifyAPI::Clients::Rest::Admin.new(session: my_session) # Create a client with the active session and a specific API version client = ShopifyAPI::Clients::Rest::Admin.new(api_version: "unstable") # Create a client with a specific session and a specific API version client = ShopifyAPI::Clients::Rest::Admin.new(session: my_session, api_version: "unstable") ``` ### Response N/A ``` -------------------------------- ### Perform GET Request to Shopify Products Endpoint (Ruby) Source: https://shopify.github.io/shopify-api-ruby/usage/rest This example shows how to create a REST Admin client and use the `get` method to retrieve a list of products from the Shopify API. It demonstrates accessing the response body for further processing. ```ruby # Create a new client. client = ShopifyAPI::Clients::Rest::Admin.new(session: session) # Use `client.get` to request the specified Shopify REST API endpoint, in this case `products`. response = client.get(path: "products") # Do something with the returned data some_function(response.body) ``` -------------------------------- ### Start Shopify OAuth Source: https://shopify.github.io/shopify-api-ruby/usage/oauth Defines a controller action to initiate the Shopify OAuth process. This route is the entry point for users to begin authentication with Shopify. It expects shop information and prepares for the authorization request. ```ruby class ShopifyAuthController < ApplicationController def login # This method will trigger the start of the OAuth process end end ``` -------------------------------- ### Instantiate REST Admin Client Source: https://shopify.github.io/shopify-api-ruby/usage/rest This section provides examples of how to create an instance of the `ShopifyAPI::Clients::Rest::Admin` client. It shows different ways to initialize the client, with or without specifying a session and API version, and how it infers active session and API version from `ShopifyAPI::Context`. ```ruby # Create a default client with `ShopifyAPI::Context.api_version` # and the active session from `ShopifyAPI::Context.active_session` client = ShopifyAPI::Clients::Rest::Admin.new # Create a client with a specific session "my_session" client = ShopifyAPI::Clients::Rest::Admin.new(session: my_session) # Create a client with active session from `ShopifyAPI::Context.active_session` # and a specific api_version - "unstable" client = ShopifyAPI::Clients::Rest::Admin.new(api_version: "unstable") # Create a client with a specific session "my_session" and api_version "unstable" client = ShopifyAPI::Clients::Rest::Admin.new(session: my_session, api_version: "unstable") ``` -------------------------------- ### Implement REST Admin Client Pagination (Ruby) Source: https://shopify.github.io/shopify-api-ruby/usage/rest This example illustrates cursor-based pagination for REST Admin API requests using the client. It shows how to retrieve the `next_page_info` from a response and use it in subsequent requests to fetch the next page of results. ```ruby client = ShopifyAPI::Clients::Rest::Admin.new(session: session) response = client.get(path: "products", query: { limit: 10 }) next_page_info = response.next_page_info if next_page_info next_page_response =client.get(path: "products", query: { limit: 10, page_info: next_page_info }) some_function(next_page_response) end ``` -------------------------------- ### PUT Request Example Source: https://shopify.github.io/shopify-api-ruby/usage/rest Illustrates how to update an existing resource, such as a product's title, using a PUT request. ```APIDOC ## PUT /admin/api/{api_version}/products/{id}.json ### Description Updates an existing product in the Shopify store. ### Method PUT ### Endpoint `/admin/api/{api_version}/products/{id}.json` ### Parameters #### Path Parameters - **id** (Integer) - Required - The unique identifier of the product to update. #### Request Body - **product** (Object) - Required - An object containing the fields to update for the product. - **title** (String) - Optional - The new title for the product. ### Request Example ```ruby # Create a new client. client = ShopifyAPI::Clients::Rest::Admin.new # Update product title body = { product: { title: "My cool product" } } # Use `client.put` to send your request to the specified Shopify Admin REST API endpoint. # This will update product title for product with ID client.put(path: "products/.json", body: body) ``` ### Response #### Success Response (200) - **body** (Hash) - The response body containing the updated product data. - **code** (Integer) - The HTTP status code (e.g., 200). - **headers** (Hash) - The response headers. #### Response Example ```json { "product": { "id": 12345, "title": "My cool product", "body_html": "

This is an example product.

", "vendor": "Example Vendor", "product_type": "Example Type" } } ``` ``` -------------------------------- ### Get All Orders Source: https://shopify.github.io/shopify-api-ruby/usage/rest This example demonstrates how to fetch all orders from the Shopify API using the `all` method. It requires the `shopify_api` gem. ```ruby # Get all orders orders = ShopifyAPI::Orders.all ``` -------------------------------- ### Shopify Storefront API GraphQL Client Source: https://shopify.github.io/shopify-api-ruby/usage/graphql_storefront This section details how to initialize and use the `ShopifyAPI::Clients::Graphql::Storefront` client to send GraphQL queries to the Shopify Storefront API. It covers authentication using private or public Storefront access tokens and provides an example of querying collections and products. ```APIDOC ## Shopify Storefront API GraphQL Client ### Description This endpoint allows you to send GraphQL queries to the Shopify Storefront API using the `ShopifyAPI::Clients::Graphql::Storefront` class. You can authenticate using either a private or public Storefront access token. ### Method N/A (Client-side library usage) ### Endpoint N/A (Client-side library usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (for client initialization) ### Request Example ```ruby # Load the access token storefront_private_access_token = ENV['SHOPIFY_STOREFRONT_PRIVATE_ACCESS_TOKEN'] shop_url = 'your-shop-name.myshopify.com' # Initialize the client with a private Storefront access token client = ShopifyAPI::Clients::Graphql::Storefront.new(shop_url, private_token: storefront_private_access_token) # Alternatively, with a public Storefront access token: # public_access_token = ENV['SHOPIFY_STOREFRONT_PUBLIC_ACCESS_TOKEN'] # client = ShopifyAPI::Clients::Graphql::Storefront.new(shop_url, public_token: public_access_token) query = <<~QUERY { collections(first: 2) { edges { node { id products(first: 5) { edges { node { id title } } } } } } } QUERY # Make the GraphQL query # The "Shopify-Storefront-Buyer-IP" header is optional and used for server-side requests. # See https://shopify.dev/docs/api/usage/authentication#making-server-side-requests response = client.query(query: query, headers: { "Shopify-Storefront-Buyer-IP": request.remote_ip }) # Process the response data puts response.data ``` ### Response #### Success Response (200) Returns the data structure defined by the GraphQL query. #### Response Example ```json { "data": { "collections": { "edges": [ { "node": { "id": "gid://shopify/Collection/12345", "products": { "edges": [ { "node": { "id": "gid://shopify/Product/67890", "title": "Example Product 1" } } ] } } } ] } } } ``` ## API Versioning ### Description By default, the client uses the API version configured in `ShopifyAPI`. You can specify a different API version or use `"unstable"` for prerelease features. ### Method N/A (Client-side library usage) ### Endpoint N/A (Client-side library usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ruby # Initialize the client with a specific API version client_v2023_01 = ShopifyAPI::Clients::Graphql::Storefront.new( shop_url, private_token: storefront_private_access_token, api_version: "2023-01" ) # Initialize the client to use the unstable API version client_unstable = ShopifyAPI::Clients::Graphql::Storefront.new( shop_url, private_token: storefront_private_access_token, api_version: "unstable" ) ``` ### Response N/A ### Response Example N/A ``` -------------------------------- ### Specify Storefront API Version (Ruby) Source: https://shopify.github.io/shopify-api-ruby/usage/graphql_storefront This example shows how to configure the `ShopifyAPI::Clients::Graphql::Storefront` client to use a specific API version, including the `"unstable"` version for accessing prerelease features. The `api_version` parameter can be set during client initialization. ```ruby client = ShopifyAPI::Clients::Graphql::Storefront.new(shop_url, private_token: storefront_private_access_token, api_version: "unstable" ) ``` -------------------------------- ### Configure Shopify API Context Source: https://shopify.github.io/shopify-api-ruby/usage/oauth Configures the Shopify API client with essential credentials and settings, including API key, secret, version, and access scopes. This setup is necessary before initiating any API requests or OAuth flows. ```ruby ShopifyAPI::Context.setup( api_key: , api_secret_key: , api_version: , scope: , # Accepts array or string: "read_orders, write_products" or ["read_orders", "write_products"] ... ) ``` -------------------------------- ### ShopifyAPI::Clients::Rest::Admin Methods Source: https://shopify.github.io/shopify-api-ruby/usage/rest Describes the core request methods (`get`, `delete`, `post`, `put`) available on the `ShopifyAPI::Clients::Rest::Admin` client and their input parameters. ```APIDOC ## ShopifyAPI::Clients::Rest::Admin Core Methods ### Description The `ShopifyAPI::Clients::Rest::Admin` client provides four fundamental methods for interacting with the Shopify Admin API: `get`, `delete`, `post`, and `put`. Each method accepts a set of common input parameters. ### Method - `get(path:, query: nil, extraHeaders: nil, tries: nil)` - `delete(path:, query: nil, extraHeaders: nil, tries: nil)` - `post(path:, body:, query: nil, extraHeaders: nil, tries: nil)` - `put(path:, body:, query: nil, extraHeaders: nil, tries: nil)` ### Endpoint These methods make requests to the Shopify Admin API endpoints based on the `path` parameter. ### Parameters #### Input Parameters for all Methods - **path** (`String`) - Required - The API endpoint path. Can be relative (e.g., `products`) or full (e.g., `/admin/oauth/access_scopes.json`). - **query** (`Hash`) - Optional - Query parameters to append to the URL. - **extraHeaders** (`Hash`) - Optional - Additional headers to include in the request. - **tries** (`Integer`) - Optional - The maximum number of times to retry the request (must be >= 0). Defaults to `1`. #### Input Parameters for `post` and `put` Methods - **body** (`Hash`) - Required for `post` and `put` - The request body payload. ### Request Example ```ruby # Example using GET response = client.get(path: "customers", query: { "limit" => 10 }) # Example using POST response = client.post(path: "orders", body: { "order" => { "email" => "customer@example.com" } }) # Example using PUT response = client.put(path: "products/12345", body: { "product" => { "status" => "active" } }) # Example using DELETE response = client.delete(path: "customers/67890") ``` ### Response #### Success Response - The response from the API, typically a `Hash` or `Array` of hashes. #### Response Example ```json { "data": { ... } } ``` ``` -------------------------------- ### Get Session ID from Embedded App Token Source: https://shopify.github.io/shopify-api-ruby/getting_started Obtain the Shopify session ID from an authentication token provided in the HTTP request headers or URL parameters for embedded applications. Supports both online and offline sessions. ```ruby # Using shopify_id_token directly: # For online (user) sessions: ShopifyAPI::Utils::SessionUtils.current_session_id(shopify_id_token, nil, true) # For offline (store) sessions: ShopifyAPI::Utils::SessionUtils.current_session_id(shopify_id_token, nil, false) # Using session_id_from_shopify_id_token helper: # For online (user) sessions: ShopifyAPI::Utils::SessionUtils::session_id_from_shopify_id_token(id_token: id_token, online: true) # For offline (store) sessions: ShopifyAPI::Utils::SessionUtils::session_id_from_shopify_id_token(id_token: id_token, online: false) ``` -------------------------------- ### Register HTTP Webhook with Shopify in Ruby Source: https://shopify.github.io/shopify-api-ruby/usage/webhooks This Ruby code snippet demonstrates how to register an HTTP webhook for the 'orders/create' topic using `ShopifyAPI::Webhooks::Registry.add_registration`. It specifies the handler, delivery method, and the relative path for the webhook callback. This registration should be done once when the app starts. ```ruby registration = ShopifyAPI::Webhooks::Registry.add_registration(topic: "orders/create", delivery_method: :http, handler: WebhookHandler, path: 'callback/orders/create') ``` -------------------------------- ### Perform PUT Request to Update Shopify Product (Ruby) Source: https://shopify.github.io/shopify-api-ruby/usage/rest This example demonstrates how to update an existing Shopify product's title using a PUT request. It shows how to structure the request body with the desired changes and specify the product ID in the request path. ```ruby # Create a new client. client = ShopifyAPI::Clients::Rest::Admin.new # Update product title body = { product: { title: "My cool product" } } # Use `client.put` to send your request to the specified Shopify Admin REST API endpoint. # This will update product title for product with ID client.put(path: "products/.json", body: body) ``` -------------------------------- ### Remove Product Image Source: https://shopify.github.io/shopify-api-ruby/usage/rest This example demonstrates how to delete a specific image associated with a product by providing both the product ID and the image ID. It uses the `delete` method from the `ShopifyAPI::Image` class. ```ruby # Remove an existing product image product_id = 1234567 image_id = 1233211234567 ShopifyAPI::Image.delete(product_id: product_id, id: image_id) ``` -------------------------------- ### Perform Client Credentials Grant and Get Session Source: https://shopify.github.io/shopify-api-ruby/usage/oauth Performs the client credentials grant to exchange the app's client ID and secret for an access token, returning a new Session object. This method is suitable for apps within your own organization and should not be used for browser-based web apps that require user authorization. ```ruby # `shop` is the shop domain name - "this-is-my-example-shop.myshopify.com" def authenticate(shop) session = ShopifyAPI::Auth::ClientCredentials.client_credentials( shop: shop, ) SessionRepository.store_session(session) end ``` -------------------------------- ### Register Shopify Webhook with Field Filtering in Ruby Source: https://shopify.github.io/shopify-api-ruby/usage/webhooks This Ruby example shows how to register an 'orders/create' webhook while filtering the data sent by Shopify. By specifying the `fields` parameter, only the 'number' and 'note' fields will be included in the webhook payload, reducing data transfer. This still requires the webhook to be handled on every update. ```ruby registration = ShopifyAPI::Webhooks::Registry.add_registration( topic: "orders/create", delivery_method: :http, handler: WebhookHandler, path: 'callback/orders/create', fields: ["number","note"] # this can also be a single comma separated string ) ``` -------------------------------- ### Get Session ID from Non-Embedded App Cookies Source: https://shopify.github.io/shopify-api-ruby/getting_started Retrieve the Shopify session ID from HTTP cookies for non-embedded applications. This function handles both online (user-specific) and offline (store-wide) sessions. ```ruby # For online (user) sessions: ShopifyAPI::Utils::SessionUtils.current_session_id(nil, cookies, true) # For offline (store) sessions: ShopifyAPI::Utils::SessionUtils.current_session_id(nil, cookies, false) ``` -------------------------------- ### Instantiate Shopify GraphQL Admin Client Source: https://shopify.github.io/shopify-api-ruby/usage/graphql Create an instance of the `ShopifyAPI::Clients::Graphql::Admin` client to make authenticated requests to the Shopify Admin GraphQL API. The client requires an active `ShopifyAPI::Auth::Session` and optionally accepts an `api_version`. If `session` is nil, it defaults to the active session from `ShopifyAPI::Context.active_session`. If `api_version` is nil, it defaults to the version set in `ShopifyAPI::Context.setup`. ```ruby client = ShopifyAPI::Clients::Graphql::Admin.new(session: session, api_version: "unstable") ``` -------------------------------- ### Implement REST Resource Pagination (Ruby) Source: https://shopify.github.io/shopify-api-ruby/usage/rest This snippet demonstrates pagination using REST resources. It shows how to fetch resources with a limit, check for the next page using `ShopifyAPI::Product.next_page?`, and retrieve subsequent pages by passing `ShopifyAPI::Product.next_page_info`. ```ruby products = ShopifyAPI::Product.all(session: session, limit: 10) loop do some_function(products) break unless ShopifyAPI::Product.next_page? products = ShopifyAPI::Product.all(session: session, limit: 10, page_info: ShopifyAPI::Product.next_page_info) end ``` -------------------------------- ### Unset Draft Order Shipping Address Source: https://shopify.github.io/shopify-api-ruby/usage/rest This example shows how to explicitly unset the shipping address for a draft order by setting `shipping_address` to an empty hash and saving the order. This is necessary because only modified values are sent to the API. ```ruby # Removes shipping address from draft_order draft_order.shipping_address = {} draft_order.save! ``` -------------------------------- ### Create Shopify Resource from Hash (Ruby) Source: https://shopify.github.io/shopify-api-ruby/usage/rest Illustrates creating a new Shopify resource, such as an order or product, by initializing it with a hash of properties using the `from_hash` constructor parameter and then saving it. ```ruby # To construct an Orders object using default session # This creates a new order object with properties provided from the hash order = ShopifyAPI::Orders.new(from_hash: {property: value}) order.save! # Create a new product from hash product_properties = { title: "My awesome product" } product = ShopifyAPI::Product.new(from_hash: product_properties) product.save! ``` -------------------------------- ### Make GraphQL API Request with Admin Client (Ruby) Source: https://shopify.github.io/shopify-api-ruby/usage/oauth Demonstrates how to instantiate a GraphQL Admin client and use it to make API requests. The client automatically uses the active session from ShopifyAPI::Context. This method is suitable for performing GraphQL operations against the Shopify Admin API. ```ruby def make_api_request # 1. Create API client without session information # The graphql_client will use `ShopifyAPI::Context.active_session` when making API calls graphql_client = ShopifyAPI::Clients::Graphql::Admin.new # 2. Use API client to make queries ... end ``` -------------------------------- ### Query Shopify Storefront API with GraphQL (Ruby) Source: https://shopify.github.io/shopify-api-ruby/usage/graphql_storefront This snippet demonstrates how to initialize the `ShopifyAPI::Clients::Graphql::Storefront` client and send a GraphQL query to the Shopify Storefront API. It supports both private and public Storefront access tokens and allows for custom headers, such as `Shopify-Storefront-Buyer-IP`. ```ruby # Load the access token as per instructions above storefront_private_access_token = '' # your shop domain shop_url = 'shop.myshopify.com' # initialize the client with session and a private Storefront access token client = ShopifyAPI::Clients::Graphql::Storefront.new(shop_url, private_token: storefront_private_access_token) # or, alternatively with a public Storefront access token: # client = ShopifyAPI::Clients::Graphql::Storefront.new(shop_url, public_token: storefront_public_access_token) query = <<~QUERY { collections(first: 2) { edges { node { id products(first: 5) { edges { node { id title } } } } } } } QUERY # You may not need the "Shopify-Storefront-Buyer-IP" header, see its documentation: # https://shopify.dev/docs/api/usage/authentication#making-server-side-requests response = client.query(query: query, headers: { "Shopify-Storefront-Buyer-IP": request.remote_ip }) # do something with the returned data ``` -------------------------------- ### ShopifyAPI::Clients::Graphql::Admin API Usage Source: https://shopify.github.io/shopify-api-ruby/usage/graphql This section details how to instantiate the GraphQL Admin client and make authenticated API calls. ```APIDOC ## ShopifyAdminGraphQL API Client ### Description This API client allows you to make authenticated requests to the Shopify Admin GraphQL API after OAuth is complete. It requires a valid `ShopifyAPI::Auth::Session`. ### Instantiation Create an instance of `ShopifyAPI::Clients::Graphql::Admin` using the current session. #### Constructor Parameters - **session** (`ShopifyAPI::Auth::Session`) - Required. The current user's session. If `nil`, the active session is inferred from `ShopifyAPI::Context.active_session`. - **api_version** (`String`) - Optional. The API version to use. Defaults to the version set in `ShopifyAPI::Context.setup`. #### Usage Example ```ruby client = ShopifyAPI::Clients::Graphql::Admin.new(session: session, api_version: "unstable") ``` ### Making Authenticated API Calls #### Basic GraphQL Query ```ruby # Initialize the client client = ShopifyAPI::Clients::Graphql::Admin.new(session: session) # Define the GraphQL query string query =<<~QUERY { products(first: 10) { edges { cursor node { id title onlineStoreUrl } } } } QUERY response = client.query(query: query) # Process the response product = response.body["data"]["products"]["edges"][0] my_function(product) ``` #### GraphQL Query with Variables ```ruby client = ShopifyAPI::Clients::Graphql::Admin.new(session: session) query = <<~QUERY query testQueryWithVariables($first: Int!){ products(first: $first) { edges { cursor node { id title onlineStoreUrl } } } } QUERY variables = { first: 3 } response = client.query(query: query, variables: variables) ``` #### GraphQL Query with Fragments ```ruby client = ShopifyAPI::Clients::Graphql::Admin.new(session: session) # Define the fragment as part of the query query = <<~QUERY fragment ProductStuff on Product { id title description onlineStoreUrl } query testQueryWithVariables($first: Int){ products(first: $first) { edges { cursor node { ...ProductStuff } } } } QUERY variables = { first: 3 } response = client.query(query: query, variables: variables) # Process the response ``` ### Response Handling #### Success Response Successful requests return a `ShopifyAPI::Clients::HttpResponse` object with the following methods: - **`code`** (`Integer`) - The HTTP response code (e.g., `200`). - **`header`** (`Hash{String, [String]}`) - The HTTP response headers. - **`body`** (`Hash{String, Untyped}`) - The HTTP response body. - **`prev_page_info`** (`String`) - Information for previous page (used in pagination). - **`next_page_info`** (`String`) - Information for next page (used in pagination). #### Failure Response Failed requests raise a `ShopifyAPI::Errors::HttpResponseError`. Error messages can be accessed via `errors.full_messages`. ### Pagination Cursor-based pagination is supported. Use `next_page_info` and `prev_page_info` from the response in subsequent requests. ### Response as Struct To receive the response body as a Struct instead of a Hash, set `response_as_struct: true` in `ShopifyAPI::Context.setup`. ```ruby ShopifyAPI::Context.setup( api_key: ShopifyApp.configuration.api_key, api_secret_key: ShopifyApp.configuration.secret, ... response_as_struct: true ) # Make a graphql query response = client.query( query: CREATE_PRODUCTS_MUTATION, variables: { input: { title: random_title, variants: [{ price: random_price }], }, }, ) # Access result with dot notation created_product2 = response.body.data.productCreate.product # Access result with hash notation created_product = response.body["data"]["productCreate"]["product"] ``` ``` -------------------------------- ### Begin Shopify OAuth Authorization Source: https://shopify.github.io/shopify-api-ruby/usage/oauth Initiates the Shopify OAuth process by calling `ShopifyAPI::Auth::Oauth.begin_auth`. This method generates an authorization URL and a session cookie. The resulting `auth_route` is used to redirect the user to Shopify for authorization, and the `cookie` should be set in the user's browser. ```ruby class ShopifyAuthController < ApplicationController def login shop = request.headers["Shop"] # Builds the authorization URL route to redirect the user to auth_response = ShopifyAPI::Auth::Oauth.begin_auth(shop: domain, redirect_path: "/auth/callback") # Store the authorization cookie cookies[auth_response[:cookie].name] = { expires: auth_response[:cookie].expires, secure: true, http_only: true, value: auth_response[:cookie].value } # Redirect the user to "auth_response[:auth_route]" to allow user to grant the app permission # This will lead the user to the Shopify Authorization page head 307 response.set_header("Location", auth_response[:auth_route]) end end ``` -------------------------------- ### Create Shopify Resource Manually (Ruby) Source: https://shopify.github.io/shopify-api-ruby/usage/rest Demonstrates creating a new Shopify resource, like a product, by instantiating the resource class and then manually assigning properties before calling the `save!` method. ```ruby # Create a new product manually product = ShopifyAPI::Product.new product.title = "Another one" product.save! ``` -------------------------------- ### Make Authenticated GraphQL API Call with Session Source: https://shopify.github.io/shopify-api-ruby/usage/oauth Demonstrates how to make an authenticated GraphQL API call using a persisted Session object. It involves retrieving the session, creating a GraphQL client with the session, executing a query, and processing the response. ```ruby def make_api_request(shop) # 1. Retrieve the Session object stored from previous step session = MyApp::SessionRepository.retrieve_session_for_shop(shop) # 2. Create API client with the session information # session must be type `ShopifyAPI::Auth::Session` graphql_client = ShopifyAPI::Clients::Graphql::Admin.new(session: session) # 3. Use API client to make queries response = graphql_client.query(query: MY_API_QUERY) # 4. Use the response for your app ... end ``` -------------------------------- ### Basic Shopify GraphQL Query Source: https://shopify.github.io/shopify-api-ruby/usage/graphql Execute a basic GraphQL query against the Shopify Admin API using an initialized `ShopifyAPI::Clients::Graphql::Admin` client. The query string is passed to the `client.query` method. The response object contains the HTTP status code, headers, and the response body, which is typically a hash containing the requested data. ```ruby # Initialize the client client = ShopifyAPI::Clients::Graphql::Admin.new(session: session) # Make the GraphQL query string query =<<~QUERY { products(first: 10) { edges { cursor node { id title onlineStoreUrl } } } } QUERY response = client.query(query: query) # do something with the response data product = response.body["data"]["products"]["edges"][0] my_function(product) ``` -------------------------------- ### Shopify OAuth Authentication Flow Source: https://shopify.github.io/shopify-api-ruby/usage/oauth This section details the steps required to implement the Shopify OAuth authentication flow, from initiating the process to handling the callback. ```APIDOC ## Shopify OAuth Flow This documentation covers the essential steps for integrating Shopify's OAuth 2.0 authorization code grant flow into your application. ### Step 1: Add a Route to Start OAuth Define a route in your application that will initiate the OAuth process. This route will typically render a button or link that, when clicked, redirects the user to Shopify for authorization. **Example (Rails Controller):** ```ruby class ShopifyAuthController < ApplicationController def login # This method will trigger the start of the OAuth process end end ``` ### Step 2: Add an OAuth Callback Route Create a route that Shopify will redirect to after the user successfully authenticates and grants permissions to your app. This route will handle the callback from Shopify. **Example (Rails Controller):** ```ruby class ShopifyCallbackController < ApplicationController def callback # This callback method will be called once user grants permission to this app from Shopify Admin. end end ``` ### Step 3: Begin OAuth Configure the Shopify API context with your application's credentials and desired access scopes. Then, use the `ShopifyAPI::Auth::Oauth.begin_auth` method to initiate the OAuth flow. **Configuration:** ```ruby ShopifyAPI::Context.setup( api_key: '', api_secret_key: '', api_version: '', scope: '', # Accepts array or string: "read_orders, write_products" or ["read_orders", "write_products"] ... ) ``` **Initiating OAuth:** ```ruby # Inside your login action (e.g., ShopifyAuthController#login) shop_domain = request.headers["Shop"] auth_response = ShopifyAPI::Auth::Oauth.begin_auth(shop: shop_domain, redirect_path: "/auth/callback") # Set the authorization cookie cookies[auth_response[:cookie].name] = { expires: auth_response[:cookie].expires, secure: true, http_only: true, value: auth_response[:cookie].value } # Redirect the user to the authorization URL head 307 response.set_header("Location", auth_response[:auth_route]) ``` **`begin_auth` Parameters:** * **`shop`** (String, Required): A Shopify domain name in the form `{exampleshop}.myshopify.com`. * **`redirect_path`** (String, Required): The redirect path used for the callback, with a leading `/`. This route must be allowed in your app settings. * **`is_online`** (Boolean, Optional, Default: `true`): Set to `true` for an online session, `false` for an offline session. * **`scope_override`** (String or Array, Optional, Default: `nil`): Overrides the access scopes configured in `ShopifyAPI::Context.setup`. If `nil`, the configured scopes are used. **`begin_auth` Output:** * **`auth_route`** (String): The URI to redirect the user to for Shopify authentication. * **`cookie`** (ShopifyAPI::Auth::Oauth::SessionCookie): A session cookie to be stored in the user's browser. ### Step 4: Handle OAuth Callback When Shopify redirects the user back to your callback route, use the `ShopifyAPI::AuthL::Oauth.validate_auth_callback` method to finalize the OAuth process. **Input Parameters for `validate_auth_callback`:** * **`cookies`** (Hash, Required): All browser cookies in a hash format. * **`auth_query`** (ShopifyAPI::Auth::Oauth::AuthQuery, Required): An `AuthQuery` object containing authorization request information. **Example (Rails Controller):** ```ruby class ShopifyCallbackController < ApplicationController def callback # Retrieve the authorization code and state from the query parameters auth_query = ShopifyAPI::Auth::Oauth::AuthQuery.new(request.query_parameters) # Validate the callback and exchange the authorization code for an access token # The result will contain session information including the access token auth_result = ShopifyAPI::Auth::Oauth.validate_auth_callback(cookies: cookies.to_h, auth_query: auth_query) # You can now use auth_result[:access_token] to make API calls on behalf of the shop # Store the shop's access token and other session details securely redirect_to '/your-app-dashboard' end end ``` ``` -------------------------------- ### Authenticated API Calls Source: https://shopify.github.io/shopify-api-ruby/usage/oauth Demonstrates how to make authenticated API calls using a persisted Session object or by setting an active session context. ```APIDOC ## Making Authenticated API Calls ### Description This section explains how to use a persisted `Session` object to make authenticated API calls to Shopify, or how to set an active session for convenience. ### Using a Persisted Session Object 1. Retrieve the `Session` object. 2. Create an API client (e.g., GraphQL Admin) with the `session` object. 3. Use the client to make API queries. ### Request Example (GraphQL) ```ruby def make_api_request(shop) # Retrieve the Session object session = MyApp::SessionRepository.retrieve_session_for_shop(shop) # Create API client with session information graphql_client = ShopifyAPI::Clients::Graphql::Admin.new(session: session) # Use API client to make queries response = graphql_client.query(query: MY_API_QUERY) # Process the response ... end ``` ### Setting the Active Session Alternatively, you can set an active session using `ShopifyAPI::Context.activate_session`. If `nil` is passed to the session parameter of API clients, they will use the active session. ### Configuration Example ```ruby def configure_app # Retrieve session session = retrieve_session_from_file # Your session retrieval logic # Activate session ShopifyAPI::Context.activate_session(session) end ``` ``` -------------------------------- ### Client Credentials Grant Source: https://shopify.github.io/shopify-api-ruby/usage/oauth This section describes how to use the client credentials grant to exchange an app's client ID and secret for an access token, suitable for apps within your own organization. ```APIDOC ## POST /oauth/client_credentials ### Description Exchanges the app's client ID and client secret for an access token using the client credentials grant. ### Method POST ### Endpoint /oauth/client_credentials ### Parameters #### Query Parameters - **shop** (String) - Required - The Shopify domain name (e.g., `{exampleshop}.myshopify.com`). ### Request Example ```ruby shop_domain = "this-is-my-example-shop.myshopify.com" session = ShopifyAPI::Auth::ClientCredentials.client_credentials( shop: shop_domain ) SessionRepository.store_session(session) ``` ### Response #### Success Response (200) - **session** (ShopifyAPI::Auth::Session) - The new `ShopifyAPI::Auth::Session` object obtained from the client credentials grant. ``` -------------------------------- ### Handle Shopify OAuth Callback Source: https://shopify.github.io/shopify-api-ruby/usage/oauth Sets up a controller action to handle the callback from Shopify after a user grants or denies app permissions. This route is crucial for completing the OAuth flow by validating the authorization response. ```ruby class ShopifyCallbackController < ApplicationController def callback # This callback method will be called once user grants permission to this app from Shopify Admin. end end ``` -------------------------------- ### Configure Shopify API Response as Struct Source: https://shopify.github.io/shopify-api-ruby/usage/graphql Configure the Shopify API client to return responses as Struct objects instead of Hashes by setting `response_as_struct: true` in `ShopifyAPI::Context.setup`. This allows accessing response data using both dot notation and hash notation, providing more flexibility. ```ruby ShopifyAPI::Context.setup( api_key: ShopifyApp.configuration.api_key, api_secret_key: ShopifyApp.configuration.secret, ... response_as_struct: true ) # Make a graphql query response = client.query( query: CREATE_PRODUCTS_MUTATION, variables: { input: { title: random_title, variants: [{ price: random_price }], }, }, ) # Access result with dot notation created_product2 = response.body.data.productCreate.product # Access result with hash notation created_product = response.body["data"]["productCreate"]["product"] ``` -------------------------------- ### Perform POST Request to Create Shopify Product (Ruby) Source: https://shopify.github.io/shopify-api-ruby/usage/rest This snippet illustrates how to create a new Shopify product using a POST request. It involves constructing a product data hash for the request body and sending it to the 'products' endpoint via the REST Admin client. ```ruby # Create a new client. client = ShopifyAPI::Clients::Rest::Admin.new(session: session) # Build your post request body. body = { product: { title: "Burton Custom Freestyle 151", body_html: "\u003cstrong\u003eGood snowboard!\u003c\/strong\u003e", vendor: "Burton", product_type: "Snowboard", } } # Use `client.post` to send your request to the specified Shopify Admin REST API endpoint. # This POST request will create a new product. client.post({ path: "products", body: body, }); ``` -------------------------------- ### Proxy GraphQL Query to Shopify Admin API (Ruby) Source: https://shopify.github.io/shopify-api-ruby/usage/graphql This Ruby code snippet demonstrates how to use ShopifyAPI::Utils::GraphqlProxy.proxy_query to send authenticated GraphQL queries to the Shopify Admin API. It accepts session, headers, raw request body, and cookies as input and returns a ShopifyAPI::Clients::HttpResponse. Error handling for invalid requests and missing sessions is included. This method is intended for non-private apps with online sessions. ```ruby def proxy begin response = ShopifyAPI::Utils::GraphqlProxy.proxy_query( session: session, headers: request.headers.to_h, body: request.raw_post, cookies: request.cookies.to_h ) render json: response.body, status: response.code rescue ShopifyAPI::Errors::InvalidGraphqlRequestError # Handle bad request rescue ShopifyAPI::Errors::SessionNotFoundError # Handle no session found end end ``` -------------------------------- ### Handle Shopify API Success and Failure Responses (Ruby) Source: https://shopify.github.io/shopify-api-ruby/usage/rest Demonstrates how to handle successful API responses by accessing `code`, `headers`, and `body` from `ShopifyAPI::Clients::HttpResponse`. It also shows how to rescue `ShopifyAPI::Errors::HttpResponseError` for failed requests and access error messages. ```ruby client = ShopifyAPI::Clients::Rest::Admin.new(session: session) response = client.get(path: "NOT-REAL") some_function(response.body) rescue ShopifyAPI::Errors::HttpResponseError => e puts fulfillment.errors.full_messages # {"errors"=>"Not Found"} # If you report this error, please include this id: bce76672-40c6-4047-b598-46208ab076f0. ``` -------------------------------- ### Shopify GraphQL Query with Variables Source: https://shopify.github.io/shopify-api-ruby/usage/graphql Perform a GraphQL query that accepts variables using the `ShopifyAPI::Clients::Graphql::Admin` client. Define the query with placeholders for variables and pass a hash of variable values to the `client.query` method. This allows for dynamic query construction and reuse. ```ruby client = ShopifyAPI::Clients::Graphql::Admin.new(session: session) query = <<~QUERY query testQueryWithVariables($first: Int!){ products(first: $first) { edges { cursor node { id title onlineStoreUrl } } } } QUERY variables = { first: 3 } response = client.query(query: query, variables: variables) ```