Thursday, November 30, 2023
No Result
View All Result
Blockchain Daily Report
Advertisement
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • METAVERSE
  • WEB3
  • SCAM ALERT
  • REGULATIONS
  • ANALYSIS
Crypto Marketcap
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • METAVERSE
  • WEB3
  • SCAM ALERT
  • REGULATIONS
  • ANALYSIS
Crypto Marketcap
Logo
No Result
View All Result
Home Web3

Solana Python API – How to Use the Solana API in Python

by Blockchain Daily Report
January 25, 2023
in Web3
Reading Time: 13 mins read
A A
0
Solana Python API – How to Use the Solana API in Python
Share on FacebookShare on Twitter


At the moment’s tutorial will present you how you can create a Python backend dapp that makes use of Solana API endpoints from Moralis. You’ll be capable to get native, fungible, and NFT balances and portfolios by pockets addresses. You’ll additionally discover ways to get NFT metadata and token costs. Due to Moralis’ Solana Python API, you may, for instance, fetch pockets balances with the next code snippet:

@app.publish(“/getWalletbalance”)
def getWalletbalance():
        physique = request.json

        params = {
            “tackle”: physique[“address”],
            “community”: physique[“network”]
            }
        consequence = sol_api.account.stability(
            api_key= moralis_api_key,
            params = params
        )
        return consequence

The traces of code for the opposite 5 endpoints are fairly comparable. Basically, they only change “getWalletbalance” and “sol_api.account.stability“. So, do you wish to discover ways to work with Moralis’ Solana Python API and implement the above traces of code, together with the opposite 5 Solana API endpoints? If that’s the case, ensure that to create your free Moralis account and observe our lead!

Overview

The core of at present’s article will probably be our Solana Python API tutorial. By following our steps, you’ll be taught to finish the preliminary setup and implement all present Moralis Solana APIs. By cloning our current frontend dapp, additionally, you will be capable to check the backend functionalities. Since we have already got a NodeJS backend dapp that covers the identical six endpoints, this tutorial additionally demonstrates how you can simply transition from NodeJS to Python. So, if you wish to discover ways to use the Solana API in Python, roll up your sleeves and observe our steps.

The sections under the tutorial embrace the theoretical features of at present’s matter. That is the place you may be taught what Solana and Python are and uncover extra particulars about Moralis’ Solana Python API and the way Moralis can additional elevate your Web3 improvement sport on Solana and different common programmable chains. In any case, the endpoints you’ll implement by finishing at present’s tutorial are only a small a part of what Moralis provides.   

Solana + Python logos

Solana Python API Tutorial

As talked about above, we are going to use the frontend we created as a part of our Solana JavaScript improvement. Which means we are going to merely change our NodeJS backend with Python with out affecting the frontend. 

Illustrative image - Replacing NodeJS backend with Python

So, right here is our easy frontend enabling you to make the most of the facility of the Solana API endpoints. In fact, the precise performance relies on the backend that we are going to concentrate on herein. Here’s a screenshot of our frontend dapp:

Endpoints outlined from the Solana Python API

Observe: If you happen to’re involved in exploring the code behind the frontend dapp, use the video on the high, beginning at 1:05. Plus, you may entry the whole frontend script – “index.html” – on GitHub. In actual fact, so as to check the backend that you just’re about to construct utilizing Python, we encourage you to clone our frontend. 

Earlier than we present you how you can use the Solana Python API, you have to full the mandatory setups. That mentioned, the next part focuses particularly on at present’s instance mission; for those who choose to make use of extra basic “Python and Web3” setup directions, ensure that to make use of our Web3 Python documentation web page.  

Python Backend Setup 

You need to have already got a “frontend” folder inside your “Solana API demo” mission that incorporates the above-mentioned “index.html” script. If you happen to determined to clone our NodeJS backend, you may need a “backend” folder there as properly. That is what we’re beginning with:

Starting a new project in Visual Studio Code called Solana Python API

Our first step is to create a “python-backend” folder. We do that by coming into the next command into our terminal:

mkdir python-backend

Then, we “cd” into this new folder:

cd python-backend

Subsequent, we create a brand new digital atmosphere for putting in and utilizing Python modules. We do that with the command under:

Python3 -m venv venv

Earlier than we are able to use the digital atmosphere, we additionally must activate it:

For that objective, we run the next command:

supply venv/bin/activate

Then, we additionally want to put in Flask, Flask CORS, Moralis, and Python “dotenv” modules:

pip set up flask flask_cors moralis python-dotenv

As soon as the above modules are put in, our digital atmosphere is prepared for use. As such, we are able to proceed with organising the atmosphere variables. That is the place we’ll retailer the Moralis Web3 API key, which is the important thing to accessing the facility of Moralis’ Solana Python API. So, in case you haven’t created your Moralis account but, ensure that to take action now. Then, you’ll be capable to copy your Web3 API key out of your admin space in two clicks:

Step 1, click on Web3 APIs tab. Step 2, copy the Web3 Solana Python API key

When you have your NodeJS backend information in the identical mission, you may merely copy the “.env” file from there and paste it into your “python-backend” folder. In any other case, create a brand new “.env” file. Inside that file, you might want to have the “MORALIS_API_KEY” variable that holds the above-obtained API key as a price.

Now that now we have our digital atmosphere prepared, we are able to concentrate on implementing Solana Python API endpoints.  

The way to Use the Solana API in Python

To implement the Solana Python API endpoints, we have to create a brand new “index.py” file inside our “python-backend” folder. On the high of that script, we import the above-installed packages:

from flask import Flask, request
from flask_cors import CORS
from moralis import sol_api
from dotenv import dotenv_values

Subsequent, we have to guarantee this script obtains our Web3 API key from the “.env” file:

config = dotenv_values(“.env”)
moralis_api_key = config.get(“MORALIS_API_KEY”)

We outline a variable “app” utilizing Flask within the following line, and we additionally embrace “CORS” in that variable:

app = Flask(__name__)
CORS(app)

We would like our backend dapp to run on port 9000 (the identical as our NodeJS backend). That approach, we don’t want to change the URL in our frontend. So, we add the next code snippet on the backside of our script:

if __name__ == “__main__”:
    app.run(debug=True, host=”0.0.0.0″, port=9000)

With the above traces of code in place, we are able to begin implementing Moralis’ Solana API endpoints:

Steadiness API endpoints: Get native stability by walletGet token stability by walletGet portfolio by pockets Token API endpoints: NFT API endpoints: Get NFTs by walletGet NFT metadata

As a substitute of ranging from scratch, you may at all times copy code snippets for every endpoint from the API reference pages contained in the Moralis documentation. Right here’s an instance:

Solana Python API documentation pages showing information and code parameters for the get native balance by wallet endpoint

Implementing Solana Python API Endpoints

In our “index.py” script, slightly below the “CORS(app)” line, we have to outline routes and capabilities for every endpoint. Beginning with the “get native stability by pockets” endpoint, the traces of code within the intro do the trick.

With “@app.publish(“/getWalletbalance”)“, we create a brand new route in Python. Then, we use “def getWalletbalance():” to outline the operate for this endpoint. Contained in the operate, we learn the JSON information with “physique = request.json“. Subsequent, we outline the endpoint’s parameter (all Moralis Solana API endpoints solely require the “tackle” and “community” parameters). Then, we use the “sol_api.account.stability” technique on our parameters and Web3 API key and retailer its information beneath the “consequence” variable. Lastly, we return outcomes by returning the “consequence” variable. Once more, listed below are the traces of code for the “getWalletbalance” endpoint:

@app.publish(“/getWalletbalance”)
def getWalletbalance():
        physique = request.json

        params = {
            “tackle”: physique[“address”],
            “community”: physique[“network”]
            }
        consequence = sol_api.account.stability(
            api_key= moralis_api_key,
            params = params
        )
        return consequence

Different endpoints observe the very same rules; we solely want to vary the routes, operate names, and strategies accordingly. Under are the snippets of code for the remaining 5 Solana Python API endpoints.

The traces of code for the “getTokenbalance” endpoint:@app.publish(“/getTokenbalance”)
def getTokenbalance():
        physique = request.json

        params = {
            “tackle”: physique[“address”],
            “community”: physique[“network”]
            }
        consequence = sol_api.account.get_spl(
            api_key= moralis_api_key,
            params = params
        )
        return consequence The traces of code for the “getNfts” endpoint:  @app.publish(“/getNfts”)
def getNfts():
        physique = request.json

        params = {
            “tackle”: physique[“address”],
            “community”: physique[“network”]
            }
        consequence = sol_api.account.get_nfts(
            api_key= moralis_api_key,
            params = params
        )
        return consequence The traces of code for the “getPortfolio” endpoint:@app.publish(“/getPortfolio”)
def getPortfolio():
        physique = request.json

        params = {
            “tackle”: physique[“address”],
            “community”: physique[“network”]
            }
        consequence = sol_api.account.get_portfolio(
            api_key= moralis_api_key,
            params = params
        )
        return consequence The traces of code for the “getNFTMetadata” endpoint:@app.publish(“/getNFTMetadata”)
def getNFTMetadata(): 
        physique = request.json

        params = {
            “tackle”: physique[“address”],
            “community”: physique[“network”]
            }
        consequence = sol_api.nft.get_nft_metadata(
            api_key= moralis_api_key,
            params = params
        )
        return consequence The traces of code for the “getTokenPrice” endpoint:@app.publish(“/getTokenPrice”)
def getTokenPrice():
        physique = request.json

        params = {
            “tackle”: physique[“address”],
            “community”: physique[“network”]
            }
        consequence = sol_api.token.get_token_price(
            api_key= moralis_api_key,
            params = params
        )
        return consequence

Observe: You may entry the whole “index.py” script in our GitHub repo. 

Testing Our Python Backend

Whereas contained in the “python-backend” folder, we use our terminal to run the “index.py” script with the next command:

Python3 index.py

This begins our backend on port 9000. Subsequent, we have to begin our frontend. We do that with the “Stay Server” extension in Visible Studio Code (VSC) by right-clicking our “index.html” script within the file tree:

Then, we use our frontend dapp by coming into the required values, choosing the community kind, and hitting the set off button. Listed here are two examples:

The “Get Native Steadiness by Pockets” function:

The “Get Token Steadiness by Pockets” function:

In fact, the opposite 4 options work in the identical method. 

Exploring Solana, Python, and the Main Web3 API Supplier

The next sections are for these of you who’re new to Solana or Python programming. These sections merely clarify what Solana and Python are, and as soon as you understand the fundamentals, you may additional discover how Moralis can support in your Solana programming endeavors.

Title - Solana

What’s Solana?

Solana is a public and open-source programmable blockchain that helps sensible contracts. The latter are referred to as “packages” on Solana. Through these on-chain packages, Solana additionally helps the creation of fungible and non-fungible tokens (NFTs) and all kinds of dapps (decentralized purposes). In case you are acquainted with Ethereum or another programmable chain, you most likely know that they often keep native cash. Solana isn’t any exception with its native coin, “SOL”. The SOL asset primarily supplies community safety through Solana’s hybrid DeFi staking consensus. SOL can also be the foreign money used to cowl transaction charges on Solana and may function a way to switch worth on the Solana chain. 

Anatoly Yakovenko and Raj Gokal are the 2 main builders who launched Solana again in 2017. Each Yakovenko and Gokal are nonetheless considerably concerned with Solana Labs – a expertise firm that builds merchandise, instruments, and reference implementations to additional develop the Solana ecosystem. 

In case you are involved in studying extra in regards to the Solana community, learn considered one of our previous articles that dive deeper into the “what’s Solana?” matter. 

Title - Python

What’s Python?

Python is a well-liked object-oriented, high-level programming language bellowed by quite a few builders. In any case, it has a fairly lengthy historical past – it’s been on the display screen since 1991. Plus, there are numerous resemblances between Python and different programming languages, resembling Ruby, Scheme, Perl, and Java. Python was designed by the developer Guido van Rossum, who sought to make it as easy as potential. Those that know and use Python declare it’s fairly simple to get began with, simple to be taught, and straightforward to make use of. Furthermore, based on “python.org“, this programming language enables you to work rapidly and combine techniques extra successfully.

In comparison with JavaScript, which continues to be the preferred programming language, Python has fewer customers. Nonetheless, it’s among the many high programming languages and is discovering its approach into Web3 improvement as properly. Apart from Solana dapps, you may also use Python for Ethereum improvement and all different EVM-compatible chains.  

Moralis landing page stating: Solana Python API - Start Building

Solana Python API by Moralis

If you happen to took on at present’s tutorial, you had an opportunity to be taught in regards to the present Moralis Solana API endpoints. You even had a chance to implement them utilizing the Solana Python API – the instrument that allows you to develop dapps on Solana utilizing Python. As such, you now know how you can fetch NFT metadata, pockets portfolios, token balances, SPL token costs, and extra. As such, you should utilize this superb instrument to create killer dapps. For example, you may construct NFT marketplaces, token worth feeds, portfolio apps, and even Web3 video games. Moralis additionally helps each the Solana mainnet and Solana devnet. The latter allows you to check your dapps earlier than taking them dwell.

There’s one other useful gizmo you should utilize when creating decentralized purposes – Moralis’ Web3 Auth API. The latter allows you to implement Web3 signups and logins on Solana and lots of different blockchains. So, other than the Solana Python API, Moralis allows you to use Python to create dapps on all main blockchains. Whenever you concentrate on Ethereum and EVM-compatible chains, you may also hearken to sensible contracts and real-time pockets occasions with the Moralis Streams API. This additional expands the vary of functionalities you may cowl along with your dapps. 

If you happen to’d wish to discover different improvement matters and observe alongside in different step-by-step tutorials, ensure that to take a look at how you can “create ERC20 token” and get Goerli ETH. Or, discover how you can simply calculate gwei to ether utilizing an already-developed calculator!   

Solana Python API – The way to Use the Solana API in Python – Abstract

Solana is without doubt one of the hottest non-EVM-compatible blockchains. On the identical time, Python continues to realize recognition amongst Web3 builders. With that in thoughts, figuring out how you can take advantage of a dependable Solana Python API could make all of the distinction when growing dapps. Due to at present’s tutorial, you understand that to begin working with this highly effective API instrument, you solely want a free Moralis account. 

In case you are severe about Solana improvement, you must also know how you can reply the “what’s a Solana pockets?” query. In time, you’ll additionally wish to discover Solana sensible contract constructing. Nonetheless, you can begin by taking a look at some Solana sensible contract examples. In any case, the correct of verified contract is without doubt one of the important Solana NFT mint instruments and arguably the simplest technique to create NFTs. 

Whether or not you wish to concentrate on constructing dapps on Solana or another main blockchain, Moralis has your again. You need to use JS, Python, or many different Moralis SDKs to affix the Web3 revolution. Plus, Moralis’ YouTube channel and crypto weblog might help you develop into a Web3 developer without spending a dime.

Nonetheless, it’s possible you’ll be involved in taking a extra skilled strategy to your blockchain improvement. In that case, it is best to contemplate enrolling in Moralis Academy. There, you’ll get to attend many pro-grade programs, such because the “Solana Programming 101” course!



Source link

Tags: APIPythonSolana
Share77Tweet48

Related Posts

How Many Blockchains Are There, and What Are the Different Types?

How Many Blockchains Are There, and What Are the Different Types?

by Blockchain Daily Report
November 29, 2023
0

The Web3 area is huge, and it’s rising greater and greater on daily basis. And never solely are we seeing...

Moralis Dapp Store – Exploring the Web3 Wiki

Moralis Dapp Store – Exploring the Web3 Wiki

by Blockchain Daily Report
November 27, 2023
0

Navigating the huge Web3 panorama – characterised by speedy progress and myriads of decentralized purposes (dapps) – could be difficult....

Best NFT Data Analytics for 2024

Best NFT Data Analytics for 2024

by Blockchain Daily Report
November 24, 2023
0

Entry to real-time and historic NFT information is crucial if you wish to analyze the market and construct NFT-based Web3...

Gnosis Chain Deep Dive – Why Build on Gnosis Chain?

Gnosis Chain Deep Dive – Why Build on Gnosis Chain?

by Blockchain Daily Report
November 22, 2023
0

Until you’ve been dwelling below a rock, odds are you’re accustomed to the scalability problems with Ethereum. These limitations pose...

Let’s use Web3 to grow projects that fight climate change

Let’s use Web3 to grow projects that fight climate change

by Blockchain Daily Report
November 21, 2023
0

Lots has been stated in regards to the potential of blockchain and different Web3 options to rework carbon credit score...

Load More
  • Trending
  • Comments
  • Latest
Arbitrum Sepolia Faucet – How to Claim Arbitrum Sepolia Testnet Funds

Arbitrum Sepolia Faucet – How to Claim Arbitrum Sepolia Testnet Funds

October 24, 2023
New SRBMiner-Multi 2.3.7 With Dynex (DNX) and Zilliqa (ZIL) Dual-Mining on Nvidia

New SRBMiner-Multi 2.3.7 With Dynex (DNX) and Zilliqa (ZIL) Dual-Mining on Nvidia

October 4, 2023
MiniBit 1366 and MiniBit 1397 Single-Chip Bitcoin ASIC Home Miners Powered by Bitaxe

MiniBit 1366 and MiniBit 1397 Single-Chip Bitcoin ASIC Home Miners Powered by Bitaxe

October 26, 2023
Digital Artists Making Waves in 2023

Digital Artists Making Waves in 2023

September 24, 2023
Mint from Etherscan – How to Mint from Contract Using Etherscan

Mint from Etherscan – How to Mint from Contract Using Etherscan

January 6, 2023
Is Meme Kombat ($MK) The Next Big Crypto Game – Video Review

Is Meme Kombat ($MK) The Next Big Crypto Game – Video Review

September 28, 2023
$4.3 million raised in presale. Is Shiba Memu set to explode in 2024?

$4.3 million raised in presale. Is Shiba Memu set to explode in 2024?

November 4, 2023
Nike x RTFKT Unbox NFT-Enriched Dunk Genesis Sneakers

Nike x RTFKT Unbox NFT-Enriched Dunk Genesis Sneakers

October 9, 2023
TRAME Revolutionizes Art in Miami Art Week 2023

TRAME Revolutionizes Art in Miami Art Week 2023

November 30, 2023
Avalanche Rally Just Getting Started?

Avalanche Rally Just Getting Started?

November 30, 2023
Borrowing USDC Is Very Expensive On Aave And Compound, What’s Going On?

Borrowing USDC Is Very Expensive On Aave And Compound, What’s Going On?

November 30, 2023
Ethereum Price Rally In Jeopardy? Key Supports To Watch Out In Short-Term

Ethereum Price Rally In Jeopardy? Key Supports To Watch Out In Short-Term

November 30, 2023
ZipMex Offers Creditors 3.35 Cents Per Dollar Owed In $97 Million Fiasco

ZipMex Offers Creditors 3.35 Cents Per Dollar Owed In $97 Million Fiasco

November 30, 2023
Celo Developer Proposes Mid-January Timeline for Evaluating Closely Watched Layer-2 Move

Celo Developer Proposes Mid-January Timeline for Evaluating Closely Watched Layer-2 Move

November 30, 2023
Binance to fully phase out BUSD by end of December

Binance to fully phase out BUSD by end of December

November 29, 2023
Survive the Startup Graveyard — This CEO Reveals What It Takes

Survive the Startup Graveyard — This CEO Reveals What It Takes

November 30, 2023
Facebook Twitter Instagram Youtube RSS

Find the latest Bitcoin, Ethereum, blockchain, crypto, Business, Fintech News, interviews, and price analysis at Blockchain Daily Report.

CATEGORIES

  • Altcoin
  • Analysis
  • Bitcoin
  • Blockchain
  • Crypto Exchanges
  • Crypto Mining
  • Crypto Updates
  • DeFi
  • Ethereum
  • Metaverse
  • NFT
  • Regulations
  • Scam Alert
  • Uncategorized
  • Web3

SITE MAP

  • Disclaimer
  • Privacy Policy
  • DMCA
  • Cookie Privacy Policy
  • Terms and Conditions
  • Contact us

Copyright © 2022 Blockchain Daily Report.
Blockchain Daily Report is not responsible for the content of external sites.

No Result
View All Result
  • HOME
  • BITCOIN
  • CRYPTO UPDATES
    • GENERAL
    • ALTCOINS
    • ETHEREUM
    • CRYPTO EXCHANGES
    • CRYPTO MINING
  • BLOCKCHAIN
  • NFT
  • DEFI
  • METAVERSE
  • WEB3
  • SCAM ALERT
  • REGULATIONS
  • ANALYSIS

Copyright © 2022 Blockchain Daily Report.
Blockchain Daily Report is not responsible for the content of external sites.

  • Stride Staked InjectiveStride Staked Injective(STINJ)$16.49-4.32%
  • bitcoinBitcoin(BTC)$37,040.00-0.54%
  • ethereumEthereum(ETH)$2,018.01-1.48%
  • USDEXUSDEX(USDEX)$1.07-0.53%
  • tetherTether(USDT)$1.00-0.01%
  • binancecoinBNB(BNB)$226.84-1.69%
  • rippleXRP(XRP)$0.60-2.13%
  • usd-coinUSDC(USDC)$1.000.03%
  • solanaSolana(SOL)$54.56-4.00%
  • staked-etherLido Staked Ether(STETH)$2,016.28-1.53%