### Go: Installing and Verifying Context-Go-SDK Source: https://docs.context.dev/guides/get-started/troubleshooting Resolve Go module errors by initializing your project with `go mod init`, installing the SDK using `go get`, and cleaning up dependencies with `go mod tidy`. Verify installation with `go list`. ```bash # Initialize a module if your project does not have go.mod yet go mod init your/module # Install the SDK go get github.com/context-dot-dev/context-go-sdk # Clean up module requirements go mod tidy # Verify installation go list -m github.com/context-dot-dev/context-go-sdk ``` -------------------------------- ### Install Context.dev Go SDK Source: https://docs.context.dev/guides/get-started/quickstart Installs the official Context.dev Go module using the go get command. ```bash go get github.com/context-dot-dev/context-go-sdk ``` -------------------------------- ### Install context.dev SDK (npm) Source: https://docs.context.dev/guides/get-started/quickstart Install the official context.dev npm package using npm. ```bash npm install context.dev ``` -------------------------------- ### Install context.dev Gem (Direct) Source: https://docs.context.dev/guides/get-started/quickstart Install the context.dev gem directly using the gem install command. ```bash gem install context.dev ``` -------------------------------- ### Install context.dev Gem (Bundle) Source: https://docs.context.dev/guides/get-started/quickstart Install the context.dev gem after adding it to the Gemfile using bundle install. ```bash bundle install ``` -------------------------------- ### Install context.dev SDK (pip) Source: https://docs.context.dev/guides/get-started/quickstart Install the official context.dev Python package using pip. ```bash pip install context.dev ``` -------------------------------- ### Go AI Query Example Source: https://docs.context.dev/api-reference/web-extraction/query-website-data-using-ai An example of querying website data with AI using the Go SDK. This requires setting up the client with an API key and handling potential errors. ```go package main import ( "context" "fmt" "github.com/context-dot-dev/context-go-sdk" "github.com/context-dot-dev/context-go-sdk/option" ) func main() { client := contextdev.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.AI.AIQuery(context.TODO(), contextdev.AIAIQueryParams{ DataToExtract: []contextdev.AIAIQueryParamsDataToExtract{{ DatapointDescription: "datapoint_description", DatapointExample: "datapoint_example", DatapointName: "datapoint_name", DatapointType: "text", }}, Domain: "domain", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.DataExtracted) } ``` -------------------------------- ### Install SDK and Zod for TypeScript Source: https://docs.context.dev/guides/use-cases/extract-structured-data Install the Context.Dev SDK and the Zod library for schema definition and validation in TypeScript projects. ```bash npm install context.dev zod ``` -------------------------------- ### JavaScript Example Source: https://docs.context.dev/api-reference/web-extraction/query-website-data-using-ai Demonstrates how to import and use the ContextDev library in JavaScript to query website data. ```JavaScript import ContextDev from 'context.dev'; ``` -------------------------------- ### Complete Brand Data Retrieval Example (Python) Source: https://docs.context.dev/guides/get-started/quickstart A complete example demonstrating how to retrieve and print detailed brand information, including error handling for API and general exceptions. ```python import context_dev import os def get_brand_data(domain): client = context_dev.ContextDev( api_key="your-api-key-here", ) try: response = client.brand.retrieve(domain=domain) brand = response.brand print(f"Company: {brand.title}") print(f"Description: {brand.description}") print(f"Colors: {brand.colors}") print(f"Logos: {brand.logos}") return brand except context_dev.APIError as e: print(f"API Error: {e.status_code} - {e.message}") raise except Exception as e: print(f"Error: {e}") raise # Usage brand_data = get_brand_data("meta.com") ``` -------------------------------- ### Extract Styleguide (Go) Source: https://docs.context.dev/api-reference/web-extraction/scrape-styleguide Example of extracting styleguide information using the Go SDK. The client is initialized with an API key, and error handling is included. ```Go package main import ( "context" "fmt" "github.com/context-dot-dev/context-go-sdk" "github.com/context-dot-dev/context-go-sdk/option" ) func main() { client := contextdev.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Web.ExtractStyleguide(context.TODO(), contextdev.WebExtractStyleguideParams{}) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.Styleguide) } ``` -------------------------------- ### Complete Integration Example for Branded Email Generation Source: https://docs.context.dev/guides/use-cases/powering-generative-ai A full example demonstrating how to generate a brand-aware email template. It includes steps for extracting brand context, fetching brand data, formatting context, and generating the email using AI. ```typescript import Anthropic from "@anthropic-ai/sdk"; import ContextDev from "context.dev"; const anthropic = new Anthropic(); const brandClient = new ContextDev({ apiKey: process.env.CONTEXT_DEV_API_KEY }); async function generateBrandedEmail(userRequest: string, userDomain?: string) { // Step 1: Extract or use known domain let domain = userDomain; if (!domain) { const extracted = await extractBrandContext(userRequest); domain = extracted?.domain; } if (!domain) { throw new Error("Could not identify company. Please specify your domain."); } // Step 2: Fetch brand data const [brandResponse, styleguideResponse] = await Promise.all([ brandClient.brand.retrieve({ domain }), brandClient.styleguide.retrieve({ url: `https://${domain}` }) ]); // Step 3: Format brand context const brandContext = formatBrandContext({ brand: brandResponse.brand, styleguide: styleguideResponse.styleguide }); // Step 4: Generate branded email const emailTemplate = await generateBrandedContent( userRequest, brandContext, 'email' ); return { template: emailTemplate, brand: { name: brandResponse.brand.title, primaryColor: brandResponse.brand.colors?.[0]?.hex, logo: brandResponse.brand.logos?.[0]?.url } }; } // Usage const result = await generateBrandedEmail( "Create a welcome email for new customers that highlights our key features", "acme.com" ); ``` -------------------------------- ### Complete Brand Data Retrieval Example (TypeScript) Source: https://docs.context.dev/guides/get-started/quickstart A complete example demonstrating how to retrieve and log detailed brand information, including error handling for API errors. ```typescript import ContextDev from "context.dev"; const client = new ContextDev({ apiKey: "your-api-key-here", }); async function getBrandData(domain: string) { try { const response = await client.brand.retrieve({ domain }); console.log("Company:", response.brand.title); console.log("Description:", response.brand.description); console.log("Colors:", response.brand.colors); console.log("Logos:", response.brand.logos); return response.brand; } catch (error) { if (error instanceof ContextDev.APIError) { console.error("API Error:", error.status, error.message); } else { console.error("Error:", error); } throw error; } } // Usage getBrandData("meta.com").then(console.log); ``` -------------------------------- ### Ruby: Installing and Updating Context.Dev Gem Source: https://docs.context.dev/guides/get-started/troubleshooting Troubleshoot Ruby gem installation issues by updating bundler, cleaning the gem cache, and reinstalling the `context.dev` gem. Use `bundle update` for Bundler projects. ```bash # Update bundler gem update bundler # Clear gem cache gem cleanup # Reinstall gem uninstall context.dev gem install context.dev # Or with bundle bundle update context.dev ``` -------------------------------- ### Format Brand Data Example Source: https://docs.context.dev/integrations/make This example demonstrates how to format the response data from Context.dev's brand retrieval API. It shows how to access the company name, logo URL, primary color, and industry classification. ```text Company Name: {{brand.title}} Logo URL: {{brand.logos[0].url}} Primary Color: {{brand.colors[0].hex}} Industry: {{brand.industries.eic[0].industry}} ``` -------------------------------- ### Sample Prompt for Onboarding Flows Source: https://docs.context.dev/guides/use-cases/onboarding-flows This sample prompt guides the implementation of pre-filled onboarding flows using the Context.dev API. It outlines the necessary steps, including API key retrieval, data fetching, form pre-filling, and optimization. ```text Help me implement pre-filled onboarding flows using Context.dev API. Here's what I need to do: 1. Sign up for a Context.dev account at https://context.dev and get my API key 2. Implement the prefetch endpoint to start fetching brand data early when users enter their email 3. Call the /brand endpoint to retrieve company logos, descriptions, social links, and other brand assets 4. Pre-fill onboarding form fields with the fetched brand data while allowing users to override any information 5. Handle fallbacks gracefully when brand data is unavailable or incomplete 6. Optimize the onboarding flow to reduce friction and increase conversion rates Use the Context.dev API documentation at https://docs.context.dev for implementation details. Show me how to integrate this into my existing onboarding flow. ``` -------------------------------- ### Example Typography Data from Style Guide Endpoint Source: https://docs.context.dev/changelog This JSON snippet shows the detailed typography information available from the style guide endpoint, including styles for headings and paragraphs. Use this endpoint for comprehensive design system extraction. ```json { "typography": { "headings": { "h1": { "fontFamily": "Inter, sans-serif", "fontSize": "2.5rem", "fontWeight": 700, "lineHeight": "1.2", "letterSpacing": "0.025em" } }, "p": { "fontFamily": "Inter, sans-serif", "fontSize": "1rem", "fontWeight": 400, "lineHeight": "1.6", "letterSpacing": "0.01em" } } } ``` -------------------------------- ### Scrape Web Content to Markdown (Python) Source: https://docs.context.dev/api-reference/web-scraping/scrape-markdown This Python example shows how to scrape a URL and get the content as Markdown. It requires the context.dev library and your API key to be set in the environment. ```Python import os from context.dev import ContextDev client = ContextDev( api_key=os.environ.get("CONTEXT_DEV_API_KEY"), # This is the default and can be omitted ) response = client.web.web_scrape_md( url="https://example.com", ) print(response.markdown) ``` -------------------------------- ### Extract Products using Go Source: https://docs.context.dev/api-reference/web-extraction/extract-products-from-a-brands-website Implement product extraction in Go using the context-go-sdk. This example shows how to initialize the client with an API key and make the extraction call. ```go package main import ( "context" "fmt" "github.com/context-dot-dev/context-go-sdk" "github.com/context-dot-dev/context-go-sdk/option" ) func main() { client := contextdev.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.AI.ExtractProducts(context.TODO(), contextdev.AIExtractProductsParams{ OfByDomain: &contextdev.AIExtractProductsParamsBodyByDomain{ Domain: "domain", }, }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.Products) } ``` -------------------------------- ### Retrieve Brand Data (Ruby) Source: https://docs.context.dev/api-reference/brand-intelligence/retrieve-brand-data-by-domain This Ruby example demonstrates how to retrieve brand data using the ContextDev gem. Provide your API key and the domain name to get brand details. ```Ruby require "context_dev" context_dev = ContextDev::Client.new(api_key: "My API Key") brand = context_dev.brand.retrieve(domain: "domain") puts(brand) ``` -------------------------------- ### Fetch Logo with JavaScript Source: https://docs.context.dev/logolink/implementation Use the `fetch` API in JavaScript to retrieve a company logo. This example demonstrates how to get the logo as a blob and create an object URL for display. It includes basic error handling for the fetch request. ```javascript const response = await fetch( "https://logos.context.dev/?publicClientId=brandLL_xxx&domain=github.com", ); if (response.ok) { const blob = await response.blob(); const imageUrl = URL.createObjectURL(blob); document.getElementById("logo").src = imageUrl; } ``` -------------------------------- ### EIC Industry Classification Example Source: https://docs.context.dev/changelog Example of the response structure when EIC industry classification is available for a brand. ```json { "industries": { "eic": [ { "industry": "Aerospace & Defense", "subindustry": "Defense Systems & Military Hardware" } ] } } ``` -------------------------------- ### Go: Enabling Debug Logging Source: https://docs.context.dev/guides/get-started/troubleshooting Initialize the Go SDK client with `option.WithDebugLog(nil)` to enable debug logging. This example demonstrates client creation and a basic API call. ```go package main import ( "context" "log" "os" contextdev "github.com/context-dot-dev/context-go-sdk" "github.com/context-dot-dev/context-go-sdk/option" ) func main() { client := contextdev.NewClient( option.WithAPIKey(os.Getenv("CONTEXT_DEV_API_KEY")), option.WithDebugLog(nil), ) response, err := client.Brand.Get(context.Background(), contextdev.BrandGetParams{ Domain: "stripe.com", }) if err != nil { log.Println("Error:", err) return } log.Printf("Success: %+v", response) } ``` -------------------------------- ### Single Product Extraction Response Example Source: https://docs.context.dev/changelog Example response from the single product extraction endpoint, indicating if the URL is a product page, the platform, and structured product data. ```json { "is_product_page": true, "platform": "amazon", "product": { "name": "Example Product", "description": "A great product", "price": 29.99, "currency": "USD", "features": ["Feature 1", "Feature 2"], "target_audience": ["Developers"], "tags": ["software", "tools"] } } ``` -------------------------------- ### Initialize Context.dev Client (Python) Source: https://docs.context.dev/guides/get-started/quickstart Initialize the Context.dev client with your API key for basic usage in Python. ```python import context_dev import os client = context_dev.ContextDev( api_key=os.environ.get("CONTEXT_DEV_API_KEY"), ) ``` -------------------------------- ### Single Product Extraction Request Example Source: https://docs.context.dev/changelog Example request for the new beta endpoint to extract product information from a single URL. Includes URL and timeout settings. ```json { "url": "https://www.amazon.com/dp/B0EXAMPLE", "timeoutMS": 30000 } ``` -------------------------------- ### Initialize Context.dev Client (Ruby) Source: https://docs.context.dev/guides/get-started/quickstart Initialize the Context.dev client with your API key for basic usage in Ruby. ```ruby require 'context_dev' client = ContextDev::Client.new( api_key: ENV['CONTEXT_DEV_API_KEY'] ) ``` -------------------------------- ### Go: Extract Website Profile Data Source: https://docs.context.dev/guides/use-cases/extract-structured-data This Go example demonstrates extracting structured data from a website using the Context.dev SDK. It defines a `WebsiteProfile` struct, generates a JSON schema from it, and uses the SDK to extract data, validating it against the schema. ```go // go get github.com/context-dot-dev/context-go-sdk github.com/invopop/jsonschema package main import ( "context" "encoding/json" "fmt" "os" contextdev "github.com/context-dot-dev/context-go-sdk" "github.com/context-dot-dev/context-go-sdk/option" "github.com/context-dot-dev/context-go-sdk/packages/param" "github.com/invopop/jsonschema" ) type CaseStudy struct { Title string `json:"title" jsonschema:"description=Case study title." URL string `json:"url" jsonschema:"format=uri,description=Absolute URL for the case study." Customer *string `json:"customer" jsonschema:"description=Customer name if listed." } type WebsiteProfile struct { MissionStatement *string `json:"mission_statement" jsonschema:"description=The company's stated mission if one is listed." ValueProps []string `json:"value_props" jsonschema:"description=Main product or service value propositions." CaseStudies []CaseStudy `json:"case_studies" jsonschema:"description=Published customer stories or case studies." } func main() { // Build a JSON Schema from the struct, then convert it to the map[string]any // the SDK expects. reflector := jsonschema.Reflector{DoNotReference: true} schemaJSON, err := json.Marshal(reflector.Reflect(&WebsiteProfile{})) if err != nil { panic(err) } var schema map[string]any if err := json.Unmarshal(schemaJSON, &schema); err != nil { panic(err) } client := contextdev.NewClient( option.WithAPIKey(os.Getenv("CONTEXT_DEV_API_KEY")), ) response, err := client.Web.Extract(context.Background(), contextdev.WebExtractParams{ URL: "https://example.com", Schema: schema, Instructions: param.NewOpt("Extract facts from the homepage, about page, and customer story pages when available."), FactCheck: param.NewOpt(true), MaxAgeMs: param.NewOpt[int64](86_400_000), }) if err != nil { panic(err) } // Decode the returned data map into the typed struct (the Go equivalent of // validating against the schema). dataJSON, err := json.Marshal(response.Data) if err != nil { panic(err) } var profile WebsiteProfile if err := json.Unmarshal(dataJSON, &profile); err != nil { panic(err) } fmt.Printf("%+v\n", profile.CaseStudies) } ``` -------------------------------- ### Direct URL for Style Guide Extraction Source: https://docs.context.dev/changelog Use the `directUrl` parameter to specify a direct URL for style guide extraction, instead of a domain. Either `domain` or `directUrl` is required. ```http GET /brand/styleguide?directUrl=https://example.com/design-system ``` -------------------------------- ### Extract Product using Ruby Source: https://docs.context.dev/api-reference/web-extraction/extract-a-single-product-from-a-url Initializes the ContextDev client with an API key and extracts product information from a specified URL. The response is then printed to the console. ```ruby require "context_dev" context_dev = ContextDev::Client.new(api_key: "My API Key") response = context_dev.ai.extract_product(url: "https://example.com") puts(response) ``` -------------------------------- ### Prefetch Brand Data in Go Source: https://docs.context.dev/api-reference/utility/prefetch-brand-data-for-a-domain Retrieve brand data for a domain using the Go SDK. This example shows client initialization with an API key and making the prefetch request. ```go package main import ( "context" "fmt" "github.com/context-dot-dev/context-go-sdk" "github.com/context-dot-dev/context-go-sdk/option" ) func main() { client := contextdev.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Utility.Prefetch(context.TODO(), contextdev.UtilityPrefetchParams{ Domain: "domain", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.Domain) } ``` -------------------------------- ### Style Guide Components Source: https://docs.context.dev/api-reference/web-extraction/scrape-styleguide This section details the structure of style guide components, such as button and card styles, as defined in the OpenAPI specification. It includes properties like padding, font styles, border details, and CSS declarations. ```APIDOC ## OpenAPI Specification for Style Guide Components This document describes the structure of style guide components within the OpenAPI specification. ### Component Properties - **type**: (string) - The data type of the property. - **padding**: (string) - Padding value. - **minWidth**: (string) - Sampled minimum width of the button box (typically px). - **minHeight**: (string) - Sampled minimum height of the button box (typically px). - **fontSize**: (string) - Font size value. - **fontWeight**: (number) - Font weight. - **fontFamily**: (string) - Primary button typeface. - **fontFallbacks**: (array of strings) - Full ordered font list. - **textDecoration**: (string) - Text decoration style. - **textDecorationColor**: (string) - Hex color of the underline. - **boxShadow**: (string) - Computed box-shadow. - **css**: (string) - Ready-to-use CSS declaration block. ### Card Component Style - **type**: (object) - Represents the card component style. - **description**: Card component style. - **required**: An array of required properties for the card component. - **backgroundColor**: (string) - **borderColor**: (string) - Border color as CSS hex. - **borderRadius**: (string) - **borderWidth**: (string) - **borderStyle**: (string) - **padding**: (string) - **boxShadow**: (string) - **textColor**: (string) - **css**: (string) - Ready-to-use CSS declaration block. ### API Responses #### Success Response (200) - **code**: (integer) - HTTP status code indicating success. #### Error Response (400) - **description**: Bad Request. - **content**: application/json - **schema**: object - **message**: (string) - Error message. - **error_code**: (string) - Error code with enum values: `INTERNAL_ERROR`, `VALID`, `NOT_FOUND`, `FORBIDDEN`, `USAGE_EXCEEDED`, `RATE_LIMITED`, `UNAUTHORIZED`. ``` -------------------------------- ### Initialize Go SDK Client Source: https://docs.context.dev/changelog Initialize a new client for the Context.dev Go SDK. This client is used to access Context.dev services from your Go application. ```go import "github.com/context-dot-dev/context-go-sdk" client := contextdev.NewClient() ``` -------------------------------- ### Prefetch Brand Data by Email (Go) Source: https://docs.context.dev/api-reference/utility/prefetch-brand-data-by-email Fetch brand data associated with an email using the Go SDK. This example demonstrates client initialization with an API key and making the prefetch request. ```Go package main import ( "context" "fmt" "github.com/context-dot-dev/context-go-sdk" "github.com/context-dot-dev/context-go-sdk/option" ) func main() { client := contextdev.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Utility.PrefetchByEmail(context.TODO(), contextdev.UtilityPrefetchByEmailParams{ Email: "dev@stainless.com", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.Domain) } ``` -------------------------------- ### Ruby SDK - Scrape Images Source: https://docs.context.dev/api-reference/web-scraping/scrape-images Example of how to use the Ruby SDK to scrape images from a URL. ```ruby require "context_dev" context_dev = ContextDev::Client.new(api_key: "My API Key") response = context_dev.web.web_scrape_images(url: "https://example.com") puts(response) ``` -------------------------------- ### Scrape Sitemap with Go Source: https://docs.context.dev/api-reference/web-scraping/crawl-sitemap Initiate a sitemap scrape using the Go SDK. This example shows how to create a client with an API key and call the webScrapeSitemap function. ```Go package main import ( "context" "fmt" "github.com/context-dot-dev/context-go-sdk" "github.com/context-dot-dev/context-go-sdk/option" ) func main() { client := contextdev.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Web.WebScrapeSitemap(context.TODO(), contextdev.WebWebScrapeSitemapParams{ Domain: "domain", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.Domain) } ``` -------------------------------- ### Initialize ContextDev Client Source: https://docs.context.dev/api-reference/screenshot-styleguide/extract-design-system-and-styleguide-from-website This snippet shows how to initialize the ContextDev client. It requires your API key, which can be set via an environment variable. ```javascript import ContextDev from 'context.dev'; const client = new ContextDev({ apiKey: process.env['CONTEXT_DEV_API_KEY'], // This is the default and can be omitted }); ``` -------------------------------- ### Python SDK - Scrape Images Source: https://docs.context.dev/api-reference/web-scraping/scrape-images Example of how to use the Python SDK to scrape images from a URL. ```python import os from context.dev import ContextDev client = ContextDev( api_key=os.environ.get("CONTEXT_DEV_API_KEY"), # This is the default and can be omitted ) response = client.web.web_scrape_images( url="https://example.com", ) print(response.images) ``` -------------------------------- ### Crawl Website and Scrape Markdown (Go) Source: https://docs.context.dev/api-reference/web-scraping/crawl-website-%26-scrape-markdown Utilize the ContextDev Go SDK to crawl a website and extract its content as Markdown. This example shows how to initialize the client with an API key and make the request. ```Go package main import ( "context" "fmt" "github.com/context-dot-dev/context-go-sdk" "github.com/context-dot-dev/context-go-sdk/option" ) func main() { client := contextdev.NewClient( option.WithAPIKey("My API Key"), ) response, err := client.Web.WebCrawlMd(context.TODO(), contextdev.WebWebCrawlMdParams{ URL: "https://example.com", }) if err != nil { panic(err.Error()) } fmt.Printf("%+v\n", response.Metadata) } ``` -------------------------------- ### Extract Styleguide using ContextDev SDK Source: https://docs.context.dev/api-reference/screenshot-styleguide/extract-design-system-and-styleguide-from-website Use this snippet to fetch the complete styleguide of a website. Ensure you have initialized the ContextDev client with your API key. ```javascript import ContextDev from 'context.dev'; const client = new ContextDev({ apiKey: process.env['CONTEXT_DEV_API_KEY'], // This is the default and can be omitted }); const response = await client.web.extractStyleguide(); console.log(response.styleguide); ```