avatarSung Kim

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

5873

Abstract

unction_ invoke__">unwrap</span>();

<span class="hljs-comment">// Print the BTC-USD price</span>
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"BTC-USD price: {}"</span>, btc_usd_price);

}</pre></div><p id="da0e"><i>I hope this helps. Let me know if you have any other questions.</i></p><p id="2dd8">The code provided by ChatGPT mostly worked, I had to make a minor revision to Cargo.toml file to make it work, as shown below:</p><div id="5f98"><pre><span class="hljs-attr">reqwest</span> = { version = <span class="hljs-string">"0.11"</span>, features = [<span class="hljs-string">"blocking"</span>, <span class="hljs-string">"json"</span>] } <span class="hljs-attr">serde_json</span> = <span class="hljs-string">"1.0.48"</span></pre></div><h2 id="7352">Request ChatGPT to convert the code to an async function</h2><p id="48db">I also tried “convert the code to async function” as shown below:</p><figure id="b3d5"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*ddUmAiWaWv2iccOF0_P7pQ.png"><figcaption></figcaption></figure><p id="dd97">and it produced the following:</p><p id="c8d7"><i>Here is an example of how you might convert the code from the previous example to use async/await in Rust:</i></p><div id="e662"><pre><span class="hljs-keyword">extern</span> <span class="hljs-keyword">crate</span> reqwest; <span class="hljs-keyword">extern</span> <span class="hljs-keyword">crate</span> serde_json;

<span class="hljs-keyword">use</span> reqwest::Client; <span class="hljs-keyword">use</span> serde_json::{from_str, Value}; <span class="hljs-keyword">use</span> std::error::Error;

<span class="hljs-meta">#[tokio::main]</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">fn</span> <span class="hljs-title function_">main</span>() <span class="hljs-punctuation">-></span> <span class="hljs-type">Result</span><(), <span class="hljs-type">Box</span><<span class="hljs-keyword">dyn</span> Error>> { <span class="hljs-comment">// Create a new reqwest client</span> <span class="hljs-keyword">let</span> <span class="hljs-variable">client</span> = Client::<span class="hljs-title function_ invoke__">new</span>();

<span class="hljs-comment">// Make an async GET request to the Coinbase API</span>
<span class="hljs-keyword">let</span> <span class="hljs-variable">response</span> = client
    .<span class="hljs-title function_ invoke__">get</span>(<span class="hljs-string">"https://api.coinbase.com/v2/prices/BTC-USD/spot"</span>)
    .<span class="hljs-title function_ invoke__">send</span>()
    .<span class="hljs-keyword">await</span>?;

<span class="hljs-comment">// Parse the JSON response into a Rust data structure</span>
<span class="hljs-keyword">let</span> <span class="hljs-variable">json</span>: Value = <span class="hljs-title function_ invoke__">from_str</span>(&amp;response.<span class="hljs-title function_ invoke__">text</span>().<span class="hljs-keyword">await</span>?).<span class="hljs-title function_ invoke__">unwrap</span>();

<span class="hljs-comment">// Access the BTC-USD price from the data structure</span>
<span class="hljs-keyword">let</span> <span class="hljs-variable">btc_usd_price</span> = json[<span class="hljs-string">"data"</span>][<span class="hljs-string">"amount"</span>].<span class="hljs-title function_ invoke__">as_str</span>().<span class="hljs-title function_ invoke__">unwrap</span>();

<span class="hljs-comment">// Print the BTC-USD price</span>
<span class="hljs-built_in">println!</span>(<span class="hljs-string">"BTC-USD price: {}"</span>, btc_usd_price);

<span class="hljs-title function_ invoke__">Ok</span>(())

}</pre></div><p id="17d1"><i>Here, we have replaced the <code>reqwest::blocking</code> module with the <code>reqwest</code> module and added the <code>#[tokio::main]</code> attribute to the <code>main</code> function. This enables us to use the <code>async</code> and <code>await</code> keywords to make asynchronous HTTP requests and handle the response asynchronously.</i></p><p id="ef77"><i>I hope this helps. Let me know if you have any other questions.</i></p><p id="3a1f">The code provided by ChatGPT mostly worked, I had to make a minor addition to Cargo.toml file to make it work, as shown below:</p><div id="d95c"><pre><span class="hljs-attr">tokio</span> = { version = <span class="hljs-string">"1.23.0"</span>, features = [<span class="hljs-string">"full"</span>] }</pre></div><h2 id="176a">Request ChatGPT to provide a detailed explanation of the code</h2><p id="33ac">I also tried “please explain the code in detail.” as shown below:</p><figure id="36d2"><img src="https://cdn-images-1.readmedium.com/v2/resize:fit:800/1*eiaOePVlDZ_6umAzJDaCKQ.png"><figcaption></figcaption></figure><p id="ed0c">and it produced the following:</p><p id="ab0c"><i>Sure, here is a more detailed explanation of the code in the previous example:</i></p><p id="b03d"><i>First, we import the necessary crates:</i></p><div id="d285"><pre><span class="hljs-keyword">extern</span> <span class="hljs-keyword">crate</span> reqwest; <span class="hljs-keyword">extern</span> <span class="hljs-keyword">crate</span> serde_json;

<span class="hljs-keyword">use</span> reqwest::Client; <span class="hljs-keyword">use</span> serde_json::{from_str, Value}; <span class="hljs-keyword">use</span> std::error::Error;</pre></div><p id="d0e1"><i>We use the <code>extern crate</code> declarations to specify that we are using the <code>reqwest</code> and <code>serde_json</code> crates in our project. Then, we use the <code>use</code> keyword to import the <code>Client</code> type from the <code>reqwest</code> crate and the <code>from_str</code> and <code>Value</code> types from the <code>serde_json</code> crate. We also import the <code>Error</code> trait from the <code>st

Options

d::error</code> module, which we will use later when handling errors.</i></p><p id="1536"><i>Next, we define the <code>main</code> function:</i></p><div id="4c81"><pre><span class="hljs-meta">#[tokio::main]</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">fn</span> <span class="hljs-title function_">main</span>() <span class="hljs-punctuation">-></span> <span class="hljs-type">Result</span><(), <span class="hljs-type">Box</span><<span class="hljs-keyword">dyn</span> Error>> { <span class="hljs-comment">// code here</span> }</pre></div><p id="b46e"><i>Here, we use the <code>#[tokio::main]</code> attribute to indicate that this is the main entry point for our program and that it should be executed by the Tokio runtime. The <code>async</code> keyword indicates that this function uses the async/await syntax. This means that we can use the <code>await</code> keyword to pause the execution of the function until an asynchronous operation completes, allowing other tasks to run concurrently.</i></p><p id="2fc9"><i>The <code>main</code> function also has a return type of <code>Result<(), Box<dyn Error>></code>, which indicates that it returns a <code>Result</code> type that can either be <code>Ok</code> if the function executes successfully or <code>Err</code> if an error occurs. The <code>Err</code> variant contains a <code>Box</code> containing a value of any type that implements the <code>Error</code> trait, which allows us to handle a wide range of different error types in a uniform way.</i></p><p id="c203"><i>Inside the <code>main</code> function, we create a new <code>Client</code> instance:</i></p><div id="fa7f"><pre><span class="hljs-type">let</span> <span class="hljs-variable">client</span> <span class="hljs-operator">=</span> Client::<span class="hljs-keyword">new</span>();</pre></div><p id="330d"><i>This <code>Client</code> instance is used to make asynchronous HTTP requests to the Coinbase API.</i></p><p id="233f"><i>Next, we use the <code>get()</code> method on the <code>Client</code> instance to make a GET request to the Coinbase API endpoint for the BTC-USD price:</i></p><div id="8485"><pre><span class="hljs-keyword">let</span> response = client .<span class="hljs-keyword">get</span>(<span class="hljs-string">"https://api.coinbase.com/v2/prices/BTC-USD/spot"</span>) .send() .<span class="hljs-keyword">await</span>?;</pre></div><p id="c505"><i>Here, we use the <code>await</code> keyword to pause the execution of the function until the request completes. The <code>?</code> operator is used to propagate any errors that occur during the request (e.g. if the request fails or the response is not received). If an error occurs, this will cause the <code>main</code> function to immediately return an <code>Err</code> value, which will be handled by the caller of the <code>main</code> function.</i></p><p id="5506"><i>After the request has completed, we parse the JSON response into a Rust data structure using the <code>from_str</code> function from the <code>serde_json</code> crate:</i></p><div id="f73a"><pre>let json: Value = <span class="hljs-built_in">from_str</span>(&response.<span class="hljs-built_in">text</span>().await?).<span class="hljs-built_in">unwrap</span>();</pre></div><p id="d586"><i>Here, we use the <code>await</code> keyword to pause the execution of the function until the response body is received and the <code>?</code> operator to propagate any errors that occur. Then, we use the <code>unwrap</code> method to extract the <code>Value</code> from the <code>Result</code> returned by the <code>from_str</code> function. This will cause the <code>main</code> function to panic if the JSON cannot be parsed, which is not ideal. In a real application, you should handle this error more gracefully by checking the <code>Result</code> value returned by <code>from_str</code> and handling the <code>Err</code> case appropriately.</i></p><p id="a425"><i>After the JSON has been parsed into a <code>Value</code>, we can access the BTC-USD price from the data structure:</i></p><div id="a81a"><pre><span class="hljs-built_in">let</span> btc_usd_price = json[<span class="hljs-string">"data"</span>][<span class="hljs-string">"amount"</span>].as_str().unwrap();</pre></div><p id="556e"><i>Here, we use the index operator (<code>[]</code>) to access the <code>"data"</code> and <code>"amount"</code> fields from the <code>json</code> value. The <code>as_str</code> method is used to convert the value to a string, and the <code>unwrap</code> method is used to extract the string from the <code>Option</code> returned by <code>as_str</code>.</i></p><p id="707c"><i>Finally, we print the BTC-USD price to the console:</i></p><div id="4f27"><pre><span class="hljs-built_in">println</span>!(<span class="hljs-string">"BTC-USD price: {}"</span>, btc_usd_price);</pre></div><p id="f94e"><i>This completes the main body of the <code>main</code> function. We return <code>Ok(())</code> to indicate that the function executed successfully:</i></p><div id="1842"><pre><span class="hljs-built_in">Ok</span>(())</pre></div><p id="0a5d"><i>I hope this helps. Let me know if you have any other questions.</i></p><p id="3634">It would have been helpful to provide Cargo.toml configuration, but this explanation was really helpful.</p><p id="1fba">Go try it out! You too can write a code snippet within 5 minutes or so.</p><p id="e32d"><b>I hope this short article is helpful. If you have any questions, please leave comments and feedback here.</b></p><h1 id="448b">Resources</h1><p id="fec8">The following is a resource used or referenced in this tutorial:</p><ul><li><a href="https://openai.com/blog/chatgpt/">https://openai.com/blog/chatgpt/</a></li><li><a href="https://chat.openai.com/chat">https://chat.openai.com/chat</a></li></ul></article></body>

Writing Code Snippet Using AI — OpenAI ChatGPT

How to write a code snippet using AI (OpenAI ChatGPT)

Even with GitHub Copilot, it takes an effort to write a working code to call a REST API to request information and process the response since you will need to understand the API and its methods. What if you can ask an AI to just write the code for you using simple English? That would be the ultimate time saver.

Photo by Towfiqu barbhuiya on Unsplash

So, I recently (November 30, 2022) came across a news article where OpenAI (OpenAI in partnership with Microsoft co-developed GithHub Copilot) released ‘ChatGPT’ AI system (https://openai.com/blog/chatgpt/), which interacts with you in a conversational way and people started posting about how ChatGPT can also write code for you. So, I decided to try it out.

This article is divided into three sections:

  • Request ChatGPT to write a code snippet using the Rust programming language.
  • Request ChatGPT to convert the code to an async function.
  • Request ChatGPT to provide a detailed explanation of the code.

Request ChatGPT to write a code snippet using the Rust programming language

I went to https://chat.openai.com/ and typed I wanted “write me a rust code to get BTC-USD price from coinbase” as shown below:

and it produced the following:

Unfortunately, I am not able to browse the internet and access external resources, so I am unable to provide you with a Rust code to get the BTC-USD price from Coinbase. However, I can provide you with a general outline of how you might go about implementing this functionality in Rust:

  1. You will need to use the reqwest crate to make HTTP requests to the Coinbase API. You can add reqwest to your project by including the following line in your Cargo.toml file:
reqwest = "0.10.4"

2. Import the reqwest crate in your Rust file and use the get() method to make a GET request to the Coinbase API endpoint for the BTC-USD price. The endpoint you will need to use is https://api.coinbase.com/v2/prices/BTC-USD/se>pot.

3. The response from the Coinbase API will be in JSON format, so you will need to use the serde_json crate to parse the JSON into a Rust data structure. You can add serde_json to your project by including the following line in your Cargo.toml file:

serde_json = "1.0.48"

4. Import the serde_json crate in your Rust file and use the from_str() method to parse the JSON response from the Coinbase API into a Rust data structure. You can then access the BTC-USD price from the data structure and use it as needed.

Here is an example of how your code might look:

extern crate reqwest;
extern crate serde_json;

use reqwest::blocking::Client;
use serde_json::{from_str, Value};

fn main() {
    // Create a new reqwest client
    let client = Client::new();

    // Make a GET request to the Coinbase API
    let response = client
        .get("https://api.coinbase.com/v2/prices/BTC-USD/spot")
        .send()
        .expect("Failed to send request");

    // Parse the JSON response into a Rust data structure
    let json: Value = from_str(&response.text().unwrap()).unwrap();

    // Access the BTC-USD price from the data structure
    let btc_usd_price = json["data"]["amount"].as_str().unwrap();

    // Print the BTC-USD price
    println!("BTC-USD price: {}", btc_usd_price);
}

I hope this helps. Let me know if you have any other questions.

The code provided by ChatGPT mostly worked, I had to make a minor revision to Cargo.toml file to make it work, as shown below:

reqwest = { version = "0.11", features = ["blocking", "json"] }
serde_json = "1.0.48"

Request ChatGPT to convert the code to an async function

I also tried “convert the code to async function” as shown below:

and it produced the following:

Here is an example of how you might convert the code from the previous example to use async/await in Rust:

extern crate reqwest;
extern crate serde_json;

use reqwest::Client;
use serde_json::{from_str, Value};
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // Create a new reqwest client
    let client = Client::new();

    // Make an async GET request to the Coinbase API
    let response = client
        .get("https://api.coinbase.com/v2/prices/BTC-USD/spot")
        .send()
        .await?;

    // Parse the JSON response into a Rust data structure
    let json: Value = from_str(&response.text().await?).unwrap();

    // Access the BTC-USD price from the data structure
    let btc_usd_price = json["data"]["amount"].as_str().unwrap();

    // Print the BTC-USD price
    println!("BTC-USD price: {}", btc_usd_price);

    Ok(())
}

Here, we have replaced the reqwest::blocking module with the reqwest module and added the #[tokio::main] attribute to the main function. This enables us to use the async and await keywords to make asynchronous HTTP requests and handle the response asynchronously.

I hope this helps. Let me know if you have any other questions.

The code provided by ChatGPT mostly worked, I had to make a minor addition to Cargo.toml file to make it work, as shown below:

tokio = { version = "1.23.0", features = ["full"] }

Request ChatGPT to provide a detailed explanation of the code

I also tried “please explain the code in detail.” as shown below:

and it produced the following:

Sure, here is a more detailed explanation of the code in the previous example:

First, we import the necessary crates:

extern crate reqwest;
extern crate serde_json;

use reqwest::Client;
use serde_json::{from_str, Value};
use std::error::Error;

We use the extern crate declarations to specify that we are using the reqwest and serde_json crates in our project. Then, we use the use keyword to import the Client type from the reqwest crate and the from_str and Value types from the serde_json crate. We also import the Error trait from the std::error module, which we will use later when handling errors.

Next, we define the main function:

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // code here
}

Here, we use the #[tokio::main] attribute to indicate that this is the main entry point for our program and that it should be executed by the Tokio runtime. The async keyword indicates that this function uses the async/await syntax. This means that we can use the await keyword to pause the execution of the function until an asynchronous operation completes, allowing other tasks to run concurrently.

The main function also has a return type of Result<(), Box<dyn Error>>, which indicates that it returns a Result type that can either be Ok if the function executes successfully or Err if an error occurs. The Err variant contains a Box containing a value of any type that implements the Error trait, which allows us to handle a wide range of different error types in a uniform way.

Inside the main function, we create a new Client instance:

let client = Client::new();

This Client instance is used to make asynchronous HTTP requests to the Coinbase API.

Next, we use the get() method on the Client instance to make a GET request to the Coinbase API endpoint for the BTC-USD price:

let response = client
    .get("https://api.coinbase.com/v2/prices/BTC-USD/spot")
    .send()
    .await?;

Here, we use the await keyword to pause the execution of the function until the request completes. The ? operator is used to propagate any errors that occur during the request (e.g. if the request fails or the response is not received). If an error occurs, this will cause the main function to immediately return an Err value, which will be handled by the caller of the main function.

After the request has completed, we parse the JSON response into a Rust data structure using the from_str function from the serde_json crate:

let json: Value = from_str(&response.text().await?).unwrap();

Here, we use the await keyword to pause the execution of the function until the response body is received and the ? operator to propagate any errors that occur. Then, we use the unwrap method to extract the Value from the Result returned by the from_str function. This will cause the main function to panic if the JSON cannot be parsed, which is not ideal. In a real application, you should handle this error more gracefully by checking the Result value returned by from_str and handling the Err case appropriately.

After the JSON has been parsed into a Value, we can access the BTC-USD price from the data structure:

let btc_usd_price = json["data"]["amount"].as_str().unwrap();

Here, we use the index operator ([]) to access the "data" and "amount" fields from the json value. The as_str method is used to convert the value to a string, and the unwrap method is used to extract the string from the Option returned by as_str.

Finally, we print the BTC-USD price to the console:

println!("BTC-USD price: {}", btc_usd_price);

This completes the main body of the main function. We return Ok(()) to indicate that the function executed successfully:

Ok(())

I hope this helps. Let me know if you have any other questions.

It would have been helpful to provide Cargo.toml configuration, but this explanation was really helpful.

Go try it out! You too can write a code snippet within 5 minutes or so.

I hope this short article is helpful. If you have any questions, please leave comments and feedback here.

Resources

The following is a resource used or referenced in this tutorial:

AI
OpenAI
Rust
Go
Code
Recommended from ReadMedium