infrablockchain-docs
en
en
  • InfraBlockchain
    • Learn
      • Architecture
        • Architecture
        • Network Participants
        • Parachain
          • System Parachains
      • Protocol
        • System Token
        • Transaction Fee
        • Proof of Transaction
      • Substrate
        • Learn
          • Basic
            • Cryptography
            • Blockchain Basics
            • Consensus
            • Networks and Nodes
            • Blockchain Transaction
            • Transaction Life Cycle
            • Offchain Operations
            • Light Client
            • Rust for Substrate
            • Introduction to Library
            • Architecture and Rust Libraries
            • File Architecture
            • Accounts, Addresses, and Keys
            • Transaction Format
            • Blockchain Randomness
          • FRAME
            • FRAME Pallets
            • FRAME Macros
            • Custom Pallets
            • Pallet Coupling
            • Origin
            • Events and Erros
            • Runtime Storage
            • State Transitions and Storage
            • SCALE Encoding
            • Weight and Fee
            • Runtime API
            • Runtime Development
          • Account
          • Address Format
          • Glossary
          • CLI
            • Archive
            • Memory Profiler
            • Node Template
            • sidecar
            • srtool
            • Subkey
            • subxt
            • try-runtime
            • tx-wrapper
          • Runtime Development
            • Basics
              • Configure Genesis State
              • Configure Runtime Constants
              • Customize a Chain Spec
              • Import a Pallet
              • Use Helper Function
            • Consensus Model
              • PoW
              • Create a Hybrid Node
            • Offchain Worker
              • Request Offchain HTTP
              • Offchain Indexing
              • Offchain Local Storage
            • Pallet Design
              • Create a Storage Structure
              • Implement Lockable Currency
              • Incorporate Randomness
              • Loose Coupling
              • Tight Coupling
            • Parachain Development
              • Add HRMP Channel
              • Add Paranodes
              • Connect to a Local Relay Chain
              • Convert a Solo Chain
              • Prepare to Launch
              • Select Collator
              • Upgrade a Parachain
            • Storage Migration
              • Basics
              • Trigger Migration
            • Test
              • Basics
              • Test a Transfer Transaction
            • Tools
              • Create a TxWrapper
              • Use Sidecar
              • try-runtime
              • Verify WASM
            • Weigths
              • Benchmark
              • Calculate Fees
              • Use Conditional Weights
              • Use Custom Weights
        • Build
          • Decide What to Build
          • Build Process
          • Determinisitc Runtime
          • Chain Spec
          • Genesis Configuration
          • Application Development
          • RPC
          • Troubleshoot Your Code
        • Tutorials
          • Install
            • Developer Tools
            • Linux
            • macOS
            • Rust Toolchain
            • Issues
            • Windows
          • Quick Start
            • Explore the Code
            • Modify Runtime
            • Start a Node
            • Substrate Basics
          • Build a Blockchain
            • Add Trusted Nodes
            • Authorize Specific Nodes
            • Build a Local Blockchain
            • Simulate Network
            • Upgrade a Running Network
          • Build Application Logic
            • Add a Pallet
            • Add Offchasin Workers
            • Publish Custom Pallets
            • Specify Origin for a Call
            • Use Macros in a Custom Pallet
          • Integrate with Tools
            • Access EVM Accounts
            • EVM Integration
            • Explore Sidecar Endpoints
            • Integrate a Light Client Node
          • Smart Contracts
            • Strategy
            • Build a Token Contract
            • Develop a Smart Contract
            • Prepare Your First Contract
            • Troubleshoot Smart Contracts
            • Use Maps for Storing Values
      • XCM
        • XCM
        • XCM Format
    • Service Chains
      • InfraDID
      • InfraEVM
      • URAuth(Universal Resource Auth)
    • DevOps
      • Build
      • Deploy
      • Monitoring
      • Runtime Upgrade
    • Tutorials
      • Basic
        • How to Interact with System Token
        • How To Pay Transaction Fee
        • How To Vote with TaaV
        • Hot to Get Validator Reward
      • Build
        • Build InfraRelayChain
        • Build Parachain
        • Open Message Passing Channels
        • Transfer Assets with XCM
      • Test
        • Benchmark
        • Check Runtime
        • Debug
        • Simulate Parachains
        • Unit Testing
      • Service Chains
        • Play with InfraDID
          • Build
          • Add Keys
          • Add Service Endpoint
          • Create InfraDID
        • Play with InfraEVM
          • Build
          • Deposit and Withdraw Token
          • Deploy ERC20 Contract
          • Deploy ERC721 Contract
          • Deploy ERC1155 Contract
  • Newnal Data Market
Powered by GitBook
On this page
  • Set a deadline and instantiate an HTTP request
  • Read and submit the response
  • Examples
  1. InfraBlockchain
  2. Learn
  3. Substrate
  4. Learn
  5. Runtime Development
  6. Offchain Worker

Request Offchain HTTP

Illustrates how to use an offchain worker to make HTTP requests.

PreviousOffchain WorkerNextOffchain Indexing

Last updated 1 year ago

Because most blockchains can't access data that's hosted on servers outside of their own network, they typically use external third-party services—oracles—to pull information in from or push information out to locations that are outside of the network. For Substrate-based blockchains, offchain workers (OCW) provide similar capabilities, but with the advantage of being able to access on-chain state.

This guide illustrates how to use an offchain worker to make HTTP requests using GET or POST methods. In the example in this guide, you'll see how to retrieve the price of Bitcoin from the cryptocompare API and how to submit data using an offchain worker API.

You might know that Rust provides its own libraries for issuing HTTP requests. However, offchain workers run in their own WebAssembly execution environment—a environment—and, therefore, don't have access to the standard Rust libraries. Instead, Substrate provides its own libraries that you can use to issue HTTP requests.

The Substrate HTTP library supports the following methods:

  • GET

  • POST

  • PUT

  • PATCH

  • DELETE

Set a deadline and instantiate an HTTP request

In most cases, you want to limit the time allowed for an offchain worker to execute its operations. For this example, you can set a hard-coded deadline of two seconds to complete the external call. You can also wait indefinitely for the response. However, waiting indefinitely might result in a timeout from the external host machine.

  1. Create a deadline of 2 seconds.

    let deadline = sp_io::offchain::timestamp().add(Duration::from_millis(2_000));
  2. Initiate an external HTTP GET request.

    let request = http::Request::get("https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD");
    let pending = request.deadline(deadline).send().map_err(|_| http::Error::IoError)?;
    let response = pending.try_wait(deadline).map_err(|_| http::Error::DeadlineReached)??;

Read and submit the response

  1. Check the response status code.

    // Let's check the status code before we proceed to reading the response.
    if response.code != 200 {
      log::warn!("Unexpected status code: {}", response.code);
      return Err(http::Error::Unknown)
    }
  2. Read the response.

    let body = response.body().collect::<Vec<u8>>();
    // Create a str slice from the body.
    let body_str = sp_std::str::from_utf8(&body).map_err(|_| {
      log::warn!("No UTF8 body");
      http::Error::Unknown
    })?;
  3. Submit data to an API using a POST request.

     // Send a POST request
    let request_body = Vec::new();
    let request = http::Request::post("https://reqres.in/api/users", vec![request_body.clone()])
      .add_header("x-api-key", "test_api_key")
      .add_header("content-type", "application/json");
    
    let pending = request
      .deadline(deadline)
      .body(vec![request_body.clone()])
      .send()
      .map_err(|_| http::Error::IoError)?;
    
    // Wait for response
    let response = pending
      .try_wait(deadline)
      .map_err(|_| http::Error::DeadlineReached)??;

Examples

no-std
Example pallet: Offchain worker
Demo: OCW pallet
Source: Substrate core primitives