Struct shopify_api::Shopify

source ·
pub struct Shopify {
    pub api_version: String,
    /* private fields */
}

Fields§

§api_version: String

Implementations§

source§

impl Shopify

source

pub async fn get_bulk_by_id(&self, id: &str) -> Option<ShopifyBulk>

Query graphql shopify api

§Example
use shopify_api::*;
use shopify_api::utils::ReadJsonTreeSteps;
use serde::{Deserialize};

#[derive(Deserialize)]
struct Shop {
   name: String,
}

#[tokio::main]
async fn main() {
  let shopify = Shopify::new(env!("TEST_SHOP_NAME"), env!("TEST_KEY"), String::from("2024-04"), None);
  let graphql_query = r#"{
     products {
        edges {
         node {
            id
            title
         }
        }
    }
  }"#;

  let variables = serde_json::json!({});
  let products_bulk = shopify.make_bulk_query(graphql_query).await.unwrap();

  shopify.wait_for_bulk(&products_bulk.bulk_operation.as_ref().unwrap().id.as_ref().unwrap()).await.unwrap();

  let bulk_status = shopify.get_bulk_by_id(&products_bulk.bulk_operation.unwrap().id.unwrap()).await.unwrap();
}

source

pub async fn make_bulk_query( &self, query: &str ) -> Result<ShopifyBulkOperationRunQuery, ShopifyAPIError>

Executes a GraphQL bulk query on the Shopify API.

§Arguments
  • query - The GraphQL query to execute in bulk.
§Returns

Result<ShopifyBulkOperationRunQuery, ShopifyAPIError> - A result containing the bulk operation or an error.

§Example
let bulk_query = "{ products { edges { node { id title } } } }";
let result = shopify.make_bulk_query(bulk_query).await?;
source

pub async fn make_bulk_mutation( &self, mutation_string: &str, staged_upload_path: &str ) -> Result<ShopifyBulkOperationRunQuery, ShopifyAPIError>

Executes a bulk mutation on the Shopify API.

§Arguments
  • mutation_string - The string representing the mutation.
  • staged_upload_path - The path for the staged upload.
§Returns

Result<ShopifyBulkOperationRunQuery, ShopifyAPIError> - A result containing the bulk operation or an error.

§Example
let mutation_string = "{ updateProducts(...) { ... } }";
let staged_upload_path = "/path/to/upload";
let result = shopify.make_bulk_mutation(mutation_string, staged_upload_path).await?;
source

pub async fn wait_for_bulk( &self, id: &str ) -> Result<ShopifyBulk, ShopifyAPIError>

Waits for the specified bulk operation to complete.

§Arguments
  • id - The identifier of the bulk operation.
§Returns

Result<ShopifyBulk, ShopifyAPIError> - The final status of the bulk operation or an error.

§Example
let bulk_id = "123456";
let bulk_status = shopify.wait_for_bulk(bulk_id);
source

pub async fn download_bulk(url: &str) -> Result<Vec<Value>, ShopifyAPIError>

Downloads data from a Shopify bulk operation.

§Arguments
  • url - The URL to download the bulk operation data.
§Returns

Result<Vec<serde_json::Value>, ShopifyAPIError> - The downloaded data or an error.

§Example
let url = "https://shopify.com/bulk/123456";
let data = Shopify::download_bulk(url).await?;
source

pub async fn stage_upload_prepare( &self, params: Vec<StagedUploadsCreateInput> ) -> Result<ShopifyStagedUploadsCreateInputQuery, ShopifyAPIError>

Prepares a staged upload for a bulk operation.

§Arguments
  • params - Parameters for the staged upload.
§Returns

Result<ShopifyStagedUploadsCreateInputQuery, ShopifyAPIError> - The result of the upload preparation or an error.

§Example
let params = vec![StagedUploadsCreateInput { /* ... */ }];
let staged_upload = shopify.stage_upload_prepare(params).await?;
source

pub async fn generate_staged_upload_url( &self, filename: &str, mime_type: &str ) -> Result<StagedMediaUploadTarget, ShopifyAPIError>

Generates a URL for a staged upload.

§Arguments
  • filename - The name of the file to upload.
  • mime_type - The MIME type of the file.
§Returns

Result<StagedMediaUploadTarget, ShopifyAPIError> - The generated URL for the upload or an error.

§Example
let filename = "data.json";
let mime_type = "application/json";
let upload_url = shopify.generate_staged_upload_url(filename, mime_type).await?;
source

pub async fn stage_upload_json( &self, data: Vec<Value> ) -> Result<String, ShopifyAPIError>

Uploads a JSON file for a bulk operation.

§Arguments
  • data - The JSON data to upload.
§Returns

Result<String, ShopifyAPIError> - The key of the uploaded object or an error.

§Example
let data = vec![json!({ "key": "value" })];
let key = shopify.stage_upload_json(data).await?;
source§

impl Shopify

source

pub async fn graphql_query<ReturnType, VariablesType>( &self, graphql_query: &str, variables: &VariablesType, json_finder: &Vec<ReadJsonTreeSteps<'_>> ) -> Result<ReturnType, ShopifyAPIError>
where ReturnType: DeserializeOwned, VariablesType: Serialize,

Query graphql shopify api

§Example
use shopify_api::*;
use shopify_api::utils::ReadJsonTreeSteps;
use serde::{Deserialize};

#[derive(Deserialize)]
struct Shop {
   name: String,
}

#[tokio::main]
async fn main() {
  let shopify = Shopify::new(env!("TEST_SHOP_NAME"), env!("TEST_KEY"), String::from("2024-04"), None);
  let graphql_query = r#"
     query {
        shop {
         name
        }
    }
  "#;
  let variables = serde_json::json!({});
  let json_finder = vec![ReadJsonTreeSteps::Key("data"), ReadJsonTreeSteps::Key("shop")];
  let shop: Shop = shopify.graphql_query(graphql_query, &variables, &json_finder).await.unwrap();

  assert_eq!(shop.name, "Rust api");
}

source

pub async fn post_graphql<Q: GraphQLQuery>( &self, variables: Q::Variables ) -> Result<GraphQLResponse<Q::ResponseData>, Error>

source§

impl Shopify

source

pub async fn rest_query<ReturnType>( &self, rest_query: &ShopifyAPIRestType<'_>, json_finder: &Option<Vec<ReadJsonTreeSteps<'_>>> ) -> Result<ReturnType, ShopifyAPIError>
where ReturnType: DeserializeOwned,

Query REST shopify api

§Example
use std::collections::HashMap;
use shopify_api::*;
use shopify_api::utils::ReadJsonTreeSteps;
use shopify_api::rest::ShopifyAPIRestType;
use serde::{Deserialize};
use serde_json::json;

#[derive(Deserialize, Debug)]
struct Product {
   id: u64,
   title: String,
}

#[tokio::main]
async fn main() {
   let shopify = Shopify::new(env!("TEST_SHOP_NAME"), env!("TEST_KEY"), String::from("2024-04"), None);
  let json_finder = vec![ReadJsonTreeSteps::Key("products"), ReadJsonTreeSteps::Index(0)];

 let product: Product = shopify.rest_query(&ShopifyAPIRestType::Get("products.json", &HashMap::new()), &Some(json_finder.clone())).await.unwrap();

// Update the product title
shopify.rest_query::<serde_json::Value>(&ShopifyAPIRestType::Put(&format!("products/{}.json", product.id), &HashMap::new(), &json!({"product": {"title": "New Title"}})), &None).await.unwrap();

let product: Product = shopify.rest_query(&ShopifyAPIRestType::Get("products.json", &HashMap::new()), &Some(json_finder.clone())).await.unwrap();
assert_eq!(product.title, "New Title");

// Set the product title back to the original
shopify.rest_query::<serde_json::Value>(&ShopifyAPIRestType::Put(&format!("products/{}.json", product.id), &HashMap::new(), &json!({"product": {"title": "Hello world product"}})), &None).await.unwrap();

//let product: Product = shopify.rest_query(&ShopifyAPIRestType::Get("products.json", &HashMap::new()), &Some(json_finder.clone())).await.unwrap();

//assert_eq!(product.title, String::from("Hello world product"));

// Create a product
let product_to_delete: Product = shopify.rest_query(&ShopifyAPIRestType::Post("products.json", &HashMap::new(), &json!({"product": {"title": "New Product", "body_html":"<strong>Good snowboard!</strong>","vendor":"Burton","product_type":"Snowboard", "tags": vec!["hello world!"]}})), &Some(vec![ReadJsonTreeSteps::Key("product")])).await.unwrap();

// Delete the product
let result = shopify.rest_query::<serde_json::Value>(&ShopifyAPIRestType::Delete(&format!("products/{}.json", product_to_delete.id), &HashMap::new()), &None).await.unwrap();

assert_eq!(result, json!({}));
}
source§

impl Shopify

source

pub fn verify_hmac(&self, data: &[u8], hmac_header: &str) -> bool

source§

impl Shopify

source

pub async fn list_webhooks( &self ) -> Result<Vec<ShopifyWebhook>, ShopifyAPIError>

source

pub async fn add_webhook( &self, address: &str, topic: &str, format: &str ) -> Result<ShopifyWebhook, ShopifyAPIError>

source

pub async fn edit_webhook( &self, webhook_id: u64, new_address: &str ) -> Result<ShopifyWebhook, ShopifyAPIError>

source

pub async fn delete_webhook( &self, webhook_id: u64 ) -> Result<Value, ShopifyAPIError>

source

pub async fn webhook_auto_config( &self, desired_webhooks: Vec<(&str, &str, &str)> ) -> Result<(), ShopifyAPIError>

source§

impl Shopify

source

pub fn new( shop: &str, api_key: &str, api_version: String, shared_secret: Option<&str> ) -> Shopify

Create a new Shopify client

§Example
use shopify_api::*;
let shopify = Shopify::new("myshop", "myapikey", String::from("2024-04"), Some("mysharedsecret"));
// or without shared secret
let shopify = Shopify::new("myshop", "myapikey", String::from("2024-04"), None);
source

pub fn get_shop(&self) -> &str

Get the shop name

§Example
use shopify_api::*;
let shopify = Shopify::new("my-shop", "my-api-key", String::from("2024-04"), Some("my-shared-secret"));
assert_eq!(shopify.get_shop(), "my-shop");
source

pub fn set_api_key(&mut self, api_key: &str) -> Result<&mut Shopify, String>

Set the API Key

§Example
use shopify_api::*;
let mut shopify = Shopify::new("myshop", "myapikey", String::from("2024-04"), Some("mysharedsecret"));
shopify.set_api_key("newapikey");
§Errors

This function returns an error if the API key is empty

source

pub fn get_query_url(&self) -> &str

Get the query url

source

pub fn rest_url(&self) -> &str

Get the rest url

source

pub fn get_api_endpoint(&self, endpoint: &str) -> String

Get the API endpoint

§Example
use shopify_api::*;
let shopify = Shopify::new("myshop", "myapikey", String::from("2024-04"), Some("mysharedsecret"));

assert_eq!(shopify.get_api_endpoint("products.json"), "https://myshop.myshopify.com/admin/api/2024-04/products.json");

Trait Implementations§

source§

impl Clone for Shopify

source§

fn clone(&self) -> Shopify

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Shopify

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more