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.

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:
- You will need to use the
reqwestcrate to make HTTP requests to the Coinbase API. You can addreqwestto your project by including the following line in yourCargo.tomlfile:
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:
