Altszn.com
  • Home
  • Crypto
    • Altcoins
    • Bitcoin
    • Ethereum
    • Monero
    • XRP
    • Zcash
  • Web3
  • DeFi
  • NFTs
No Result
View All Result
Altszn.com
  • Home
  • Crypto
    • Altcoins
    • Bitcoin
    • Ethereum
    • Monero
    • XRP
    • Zcash
  • Web3
  • DeFi
  • NFTs
No Result
View All Result
Altszn.com
No Result
View All Result

Solana Python API โ€“ How to Use the Solana API in Python

Altszn.com by Altszn.com
January 24, 2023
in Web3
0
Solana Python API โ€“ How to Use the Solana API in Python
399
SHARES
2.3k
VIEWS
Share on FacebookShare on Twitter


Todayโ€™s tutorial will show you how to create a Python backend dapp that utilizes Solana API endpoints from Moralis. Youโ€™ll be able to get native, fungible, and NFT balances and portfolios by wallet addresses. Youโ€™ll also learn how to get NFT metadata and token prices. Thanks to Moralisโ€™ Solana Python API, you can, for example, fetch wallet balances with the following code snippet:

@app.post("/getWalletbalance") def getWalletbalance():         body = request.json          params = {             "address": body["address"],             "network": body["network"]             }         result = sol_api.account.balance(             api_key= moralis_api_key,             params = params         )         return result

The lines of code for the other five endpoints are pretty similar. Essentially, they just replace โ€œgetWalletbalanceโ€ and โ€œsol_api.account.balanceโ€œ. So, do you want to learn how to work with Moralisโ€™ Solana Python API and implement the above lines of code, including the other five Solana API endpoints? If so, make sure to create your free Moralis account and follow our lead!

Scale with the Solana Python API from Moralis - Sign Up Today!

Overview

The core of todayโ€™s article will be our Solana Python API tutorial. By following our steps, youโ€™ll learn to complete the initial setup and implement all current Moralis Solana APIs. By cloning our existing frontend dapp, you will also be able to test the backend functionalities. Since we already have a NodeJS backend dapp that covers the same six endpoints, this tutorial also demonstrates how to easily transition from NodeJS to Python. So, if you want to learn how to use the Solana API in Python, roll up your sleeves and follow our steps.

The sections below the tutorial include the theoretical aspects of todayโ€™s topic. This is where you can learn what Solana and Python are and discover more details about Moralisโ€™ Solana Python API and how Moralis can further elevate your Web3 development game on Solana and other popular programmable chains. After all, the endpoints youโ€™ll implement by completing todayโ€™s tutorial are just a small part of what Moralis offers.   

Solana + Python logos

Solana Python API Tutorial

As mentioned above, we will use the frontend we created as part of our Solana JavaScript development. This means that we will simply replace our NodeJS backend with Python without affecting the frontend. 

Illustrative image - Replacing NodeJS backend with Python

So, here is our simple frontend enabling you to utilize the power of the Solana API endpoints. Of course, the actual functionality depends on the backend that we will focus on herein. Here is a screenshot of our frontend dapp:

Endpoints outlined from the Solana Python API

Note: If youโ€™re interested in exploring the code behind the frontend dapp, use the video at the top, starting at 1:05. Plus, you can access the complete frontend script โ€“ โ€œindex.htmlโ€ โ€“ on GitHub. In fact, in order to test the backend that youโ€™re about to build using Python, we encourage you to clone our frontend. 

Before we show you how to use the Solana Python API, you must complete the necessary setups. That said, the following section focuses specifically on todayโ€™s example project; if you prefer to use more general โ€œPython and Web3โ€ setup instructions, make sure to use our Web3 Python documentation page.  

Python Backend Setup 

You should already have a โ€œfrontendโ€ folder inside your โ€œSolana API demoโ€ project that contains the above-mentioned โ€œindex.htmlโ€ script. If you decided to clone our NodeJS backend, you might have a โ€œbackendโ€ folder there as well. This is what we are starting 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 this by entering the following command into our terminal:

mkdir python-backend 

Then, we โ€œcdโ€ into this new folder:

cd python-backend

Next, we create a new virtual environment for installing and using Python modules. We do this with the command below:

Python3 -m venv venv

Before we can use the virtual environment, we also need to activate it:

For that purpose, we run the following command:

source venv/bin/activate

Then, we also need to install Flask, Flask CORS, Moralis, and Python โ€œdotenvโ€ modules:

pip install flask flask_cors moralis python-dotenv

Once the above modules are installed, our virtual environment is ready to be used. As such, we can proceed with setting up the environment variables. This is where weโ€™ll store the Moralis Web3 API key, which is the key to accessing the power of Moralisโ€™ Solana Python API. So, in case you havenโ€™t created your Moralis account yet, make sure to do so now. Then, youโ€™ll be able to copy your Web3 API key from your admin area in two clicks:

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

If you have your NodeJS backend files in the same project, you can simply copy the โ€œ.envโ€ file from there and paste it into your โ€œpython-backendโ€ folder. Otherwise, create a new โ€œ.envโ€ file. Inside that file, you need to have the โ€œMORALIS_API_KEYโ€ variable that holds the above-obtained API key as a value.

Now that we have our virtual environment ready, we can focus on implementing Solana Python API endpoints.  

How to Use the Solana API in Python

To implement the Solana Python API endpoints, we need to create a new โ€œindex.pyโ€ file inside our โ€œpython-backendโ€ folder. At the top 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

Next, we need to ensure this script obtains our Web3 API key from the โ€œ.envโ€ file:

config = dotenv_values(".env") moralis_api_key = config.get("MORALIS_API_KEY")

We define a variable โ€œappโ€ using Flask in the following line, and we also include โ€œCORSโ€ in that variable:

app = Flask(__name__) CORS(app)

We want our backend dapp to run on port 9000 (the same as our NodeJS backend). That way, we donโ€™t need to modify the URL in our frontend. So, we add the following code snippet at the bottom of our script:

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

With the above lines of code in place, we can start implementing Moralisโ€™ Solana API endpoints:

  • Balance API endpoints:
    • Get native balance by wallet
    • Get token balance by wallet
    • Get portfolio by wallet
  • Token API endpoints:
  • NFT API endpoints:
    • Get NFTs by wallet
    • Get NFT metadata

Instead of starting from scratch, you can always copy code snippets for each endpoint from the API reference pages inside the Moralis documentation. Hereโ€™s an example:

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, just below the โ€œCORS(app)โ€ line, we need to define routes and functions for each endpoint. Starting with the โ€œget native balance by walletโ€ endpoint, the lines of code in the intro do the trick.

With โ€œ@app.post(โ€œ/getWalletbalanceโ€)โ€œ, we create a new route in Python. Then, we use โ€œdef getWalletbalance():โ€ to define the function for this endpoint. Inside the function, we read the JSON data with โ€œbody = request.jsonโ€œ. Next, we define the endpointโ€™s parameter (all Moralis Solana API endpoints only require the โ€œaddressโ€ and โ€œnetworkโ€ parameters). Then, we use the โ€œsol_api.account.balanceโ€ method on our parameters and Web3 API key and store its data under the โ€œresultโ€ variable. Finally, we return results by returning the โ€œresultโ€ variable. Again, here are the lines of code for the โ€œgetWalletbalanceโ€ endpoint:

@app.post("/getWalletbalance") def getWalletbalance():         body = request.json          params = {             "address": body["address"],             "network": body["network"]             }         result = sol_api.account.balance(             api_key= moralis_api_key,             params = params         )         return result

Other endpoints follow the exact same principles; we only need to change the routes, function names, and methods accordingly. Below are the snippets of code for the remaining five Solana Python API endpoints.

  • The lines of code for the โ€œgetTokenbalanceโ€ endpoint:
@app.post("/getTokenbalance") def getTokenbalance():         body = request.json          params = {             "address": body["address"],             "network": body["network"]             }         result = sol_api.account.get_spl(             api_key= moralis_api_key,             params = params         )         return result
  • The lines of code for the โ€œgetNftsโ€ endpoint:  
@app.post("/getNfts") def getNfts():         body = request.json          params = {             "address": body["address"],             "network": body["network"]             }         result = sol_api.account.get_nfts(             api_key= moralis_api_key,             params = params         )         return result
  • The lines of code for the โ€œgetPortfolioโ€ endpoint:
@app.post("/getPortfolio") def getPortfolio():         body = request.json          params = {             "address": body["address"],             "network": body["network"]             }         result = sol_api.account.get_portfolio(             api_key= moralis_api_key,             params = params         )         return result
  • The lines of code for the โ€œgetNFTMetadataโ€ endpoint:
@app.post("/getNFTMetadata") def getNFTMetadata():          body = request.json          params = {             "address": body["address"],             "network": body["network"]             }         result = sol_api.nft.get_nft_metadata(             api_key= moralis_api_key,             params = params         )         return result
  • The lines of code for the โ€œgetTokenPriceโ€ endpoint:
@app.post("/getTokenPrice") def getTokenPrice():         body = request.json          params = {             "address": body["address"],             "network": body["network"]             }         result = sol_api.token.get_token_price(             api_key= moralis_api_key,             params = params         )         return result

Note: You can access the complete โ€œindex.pyโ€ script in our GitHub repo. 

Testing Our Python Backend

While inside the โ€œpython-backendโ€ folder, we use our terminal to run the โ€œindex.pyโ€ script with the following command:

Python3 index.py

This starts our backend on port 9000. Next, we need to start our frontend. We do this with the โ€œLive Serverโ€ extension in Visual Studio Code (VSC) by right-clicking our โ€œindex.htmlโ€ script in the file tree:

Then, we use our frontend dapp by entering the required values, selecting the network type, and hitting the trigger button. Here are two examples:

  • The โ€œGet Native Balance by Walletโ€ feature:
  • The โ€œGet Token Balance by Walletโ€ feature:

Of course, the other four features work in the same manner. 

Exploring Solana, Python, and the Leading Web3 API Provider

The following sections are for those of you who are new to Solana or Python programming. These sections simply explain what Solana and Python are, and once you know the basics, you can further explore how Moralis can aid in your Solana programming endeavors.

Title - Solana

What is Solana?

Solana is a public and open-source programmable blockchain that supports smart contracts. The latter are called โ€œprogramsโ€ on Solana. Via these on-chain programs, Solana also supports the creation of fungible and non-fungible tokens (NFTs) and all sorts of dapps (decentralized applications). If you are familiar with Ethereum or any other programmable chain, you probably know that they usually maintain native coins. Solana is no exception with its native coin, โ€œSOLโ€. The SOL asset primarily provides network security via Solanaโ€™s hybrid DeFi staking consensus. SOL is also the currency used to cover transaction fees on Solana and can serve as a means to transfer value on the Solana chain. 

Anatoly Yakovenko and Raj Gokal are the two leading developers who launched Solana back in 2017. Both Yakovenko and Gokal are still significantly involved with Solana Labs โ€“ a technology company that builds products, tools, and reference implementations to further expand the Solana ecosystem. 

If you are interested in learning more about the Solana network, read one of our past articles that dive deeper into the โ€œwhat is Solana?โ€ topic. 

Title - Python

What is Python?

Python is a popular object-oriented, high-level programming language bellowed by numerous developers. After all, it has a rather long history โ€“ itโ€™s been on the screen since 1991. Plus, there are many resemblances between Python and other programming languages, such as Ruby, Scheme, Perl, and Java. Python was designed by the developer Guido van Rossum, who sought to make it as straightforward as possible. Those who know and use Python claim it is rather easy to get started with, easy to learn, and easy to use. Moreover, according to โ€œpython.orgโ€œ, this programming language lets you work quickly and integrate systems more effectively.

Compared to JavaScript, which continues to be the most popular programming language, Python has fewer users. However, it is among the top programming languages and is finding its way into Web3 development as well. Aside from Solana dapps, you can also use Python for Ethereum development and all other EVM-compatible chains.  

Moralis landing page stating: Solana Python API - Start Building

Solana Python API by Moralis

If you took on todayโ€™s tutorial, you had a chance to learn about the current Moralis Solana API endpoints. You even had an opportunity to implement them using the Solana Python API โ€“ the tool that enables you to develop dapps on Solana using Python. As such, you now know how to fetch NFT metadata, wallet portfolios, token balances, SPL token prices, and more. As such, you can use this amazing tool to create killer dapps. For instance, you can build NFT marketplaces, token price feeds, portfolio apps, and even Web3 games. Moralis also supports both the Solana mainnet and Solana devnet. The latter enables you to test your dapps before taking them live.

Thereโ€™s another great tool you can use when creating decentralized applications โ€“ Moralisโ€™ Web3 Auth API. The latter enables you to implement Web3 signups and logins on Solana and many other blockchains. So, aside from the Solana Python API, Moralis enables you to use Python to create dapps on all leading blockchains. When you focus on Ethereum and EVM-compatible chains, you can also listen to smart contracts and real-time wallet events with the Moralis Streams API. This further expands the range of functionalities you can cover with your dapps. 

If youโ€™d like to explore other development topics and follow along in other step-by-step tutorials, make sure to check out how to โ€œcreate ERC20 tokenโ€ and get Goerli ETH. Or, explore how to easily calculate gwei to ether using an already-developed calculator!   

Solana Python API โ€“ How to Use the Solana API in Python โ€“ Summary

Solana is one of the most popular non-EVM-compatible blockchains. At the same time, Python continues to gain popularity among Web3 developers. With that in mind, knowing how to make the most of a reliable Solana Python API can make all the difference when developing dapps. Thanks to todayโ€™s tutorial, you know that to start working with this powerful API tool, you only need a free Moralis account. 

If you are serious about Solana development, you should also know how to answer the โ€œwhat is a Solana wallet?โ€ question. In time, youโ€™ll also want to explore Solana smart contract building. However, you can start by looking at some Solana smart contract examples. After all, the right kind of verified contract is one of the essential Solana NFT mint tools and arguably the easiest way to create NFTs. 

Whether you want to focus on building dapps on Solana or any other leading blockchain, Moralis has your back. You can use JS, Python, or many other Moralis SDKs to join the Web3 revolution. Plus, Moralisโ€™ YouTube channel and crypto blog can help you become a Web3 developer for free.

However, you may be interested in taking a more professional approach to your blockchain development. In that case, you should consider enrolling in Moralis Academy. There, youโ€™ll get to attend many pro-grade courses, such as the โ€œSolana Programming 101โ€ course!



Read More: moralis.io

Tags: APIPythonSolanaweb 3.0Web3
ADVERTISEMENT

Recent

EU to Track Crypto Transfers Under New AML Rules: Eurogroup President

EU to Track Crypto Transfers Under New AML Rules: Eurogroup President

May 8, 2025
Browser Crypto Mining in 2025: Still Worth It?

Browser Crypto Mining in 2025: Still Worth It?

May 8, 2025
Bitcoin DeFi sees surge in mining participation despite drop in TVL

Bitcoin DeFi sees surge in mining participation despite drop in TVL

May 8, 2025

Categories

  • Bitcoin (4,969)
  • Blockchain (11,649)
  • Crypto (9,590)
  • Dark Web (569)
  • DeFi (8,514)
  • Ethereum (5,036)
  • Metaverse (7,789)
  • Monero (307)
  • NFT (1,616)
  • Solana (5,105)
  • Web3 (21,051)
  • Zcash (509)

Category

Select Category

    Advertise

    Advertise your site, company or product to millions of web3, NFT and cryptocurrency enthusiasts. Learn more

    Useful Links

    Advertise
    DMCA
    Contact Us
    Privacy Policy
    Shipping & Returns
    Terms of Use

    Resources

    Exchanges
    Changelly
    Web3 Jobs

    Recent News

    EU to Track Crypto Transfers Under New AML Rules: Eurogroup President

    EU to Track Crypto Transfers Under New AML Rules: Eurogroup President

    May 8, 2025
    Browser Crypto Mining in 2025: Still Worth It?

    Browser Crypto Mining in 2025: Still Worth It?

    May 8, 2025

    ยฉ 2022 Altszn.com. All Rights Reserved.

    No Result
    View All Result
    • Home
      • Home โ€“ Layout 1
      • Home โ€“ Layout 2
      • Home โ€“ Layout 3

    ยฉ Altszn.com. All Rights Reserved.

    • bitcoinBitcoin (BTC) $ 102,644.00
    • ethereumEthereum (ETH) $ 2,194.83
    • tetherTether (USDT) $ 0.999932
    • xrpXRP (XRP) $ 2.31
    • bnbBNB (BNB) $ 625.90
    • solanaSolana (SOL) $ 162.79
    • usd-coinUSDC (USDC) $ 0.999897
    • dogecoinDogecoin (DOGE) $ 0.195260
    • cardanoCardano (ADA) $ 0.760436
    • tronTRON (TRX) $ 0.256579
    • staked-etherLido Staked Ether (STETH) $ 2,190.87
    • suiSui (SUI) $ 4.00
    • wrapped-bitcoinWrapped Bitcoin (WBTC) $ 102,584.00
    • chainlinkChainlink (LINK) $ 15.76
    • avalanche-2Avalanche (AVAX) $ 22.18
    • wrapped-stethWrapped stETH (WSTETH) $ 2,637.36
    • stellarStellar (XLM) $ 0.290978
    • shiba-inuShiba Inu (SHIB) $ 0.000014
    • bitcoin-cashBitcoin Cash (BCH) $ 416.54
    • hedera-hashgraphHedera (HBAR) $ 0.194137
    • leo-tokenLEO Token (LEO) $ 8.83
    • usdsUSDS (USDS) $ 0.999887
    • the-open-networkToncoin (TON) $ 3.19
    • hyperliquidHyperliquid (HYPE) $ 23.00
    • litecoinLitecoin (LTC) $ 94.20
    • polkadotPolkadot (DOT) $ 4.44
    • wethWETH (WETH) $ 2,193.85
    • moneroMonero (XMR) $ 296.68
    • bitget-tokenBitget Token (BGB) $ 4.49
    • binance-bridged-usdt-bnb-smart-chainBinance Bridged USDT (BNB Smart Chain) (BSC-USD) $ 0.999964
    • wrapped-eethWrapped eETH (WEETH) $ 2,340.81
    • pi-networkPi Network (PI) $ 0.667175
    • coinbase-wrapped-btcCoinbase Wrapped BTC (CBBTC) $ 102,611.00
    • ethena-usdeEthena USDe (USDE) $ 0.999365
    • pepePepe (PEPE) $ 0.000011
    • whitebitWhiteBIT Coin (WBT) $ 30.33
    • bittensorBittensor (TAO) $ 422.29
    • uniswapUniswap (UNI) $ 6.03
    • aptosAptos (APT) $ 5.52
    • daiDai (DAI) $ 1.00
    • nearNEAR Protocol (NEAR) $ 2.73
    • okbOKB (OKB) $ 52.85
    • susdssUSDS (SUSDS) $ 1.05
    • aaveAave (AAVE) $ 205.05
    • ondo-financeOndo (ONDO) $ 0.966283
    • blackrock-usd-institutional-digital-liquidity-fundBlackRock USD Institutional Digital Liquidity Fund (BUIDL) $ 1.00
    • ethereum-classicEthereum Classic (ETC) $ 18.45
    • crypto-com-chainCronos (CRO) $ 0.097663
    • internet-computerInternet Computer (ICP) $ 5.21
    • gatechain-tokenGate (GT) $ 21.73
    • bitcoinBitcoin (BTC) $ 102,644.00
    • ethereumEthereum (ETH) $ 2,194.83
    • tetherTether (USDT) $ 0.999932
    • xrpXRP (XRP) $ 2.31
    • bnbBNB (BNB) $ 625.90
    • solanaSolana (SOL) $ 162.79
    • usd-coinUSDC (USDC) $ 0.999897
    • dogecoinDogecoin (DOGE) $ 0.195260
    • cardanoCardano (ADA) $ 0.760436
    • tronTRON (TRX) $ 0.256579
    • staked-etherLido Staked Ether (STETH) $ 2,190.87
    • suiSui (SUI) $ 4.00
    • wrapped-bitcoinWrapped Bitcoin (WBTC) $ 102,584.00
    • chainlinkChainlink (LINK) $ 15.76
    • avalanche-2Avalanche (AVAX) $ 22.18
    • wrapped-stethWrapped stETH (WSTETH) $ 2,637.36
    • stellarStellar (XLM) $ 0.290978
    • shiba-inuShiba Inu (SHIB) $ 0.000014
    • bitcoin-cashBitcoin Cash (BCH) $ 416.54
    • hedera-hashgraphHedera (HBAR) $ 0.194137
    • leo-tokenLEO Token (LEO) $ 8.83
    • usdsUSDS (USDS) $ 0.999887
    • the-open-networkToncoin (TON) $ 3.19
    • hyperliquidHyperliquid (HYPE) $ 23.00
    • litecoinLitecoin (LTC) $ 94.20
    • polkadotPolkadot (DOT) $ 4.44
    • wethWETH (WETH) $ 2,193.85
    • moneroMonero (XMR) $ 296.68
    • bitget-tokenBitget Token (BGB) $ 4.49
    • binance-bridged-usdt-bnb-smart-chainBinance Bridged USDT (BNB Smart Chain) (BSC-USD) $ 0.999964
    • wrapped-eethWrapped eETH (WEETH) $ 2,340.81
    • pi-networkPi Network (PI) $ 0.667175
    • coinbase-wrapped-btcCoinbase Wrapped BTC (CBBTC) $ 102,611.00
    • ethena-usdeEthena USDe (USDE) $ 0.999365
    • pepePepe (PEPE) $ 0.000011
    • whitebitWhiteBIT Coin (WBT) $ 30.33
    • bittensorBittensor (TAO) $ 422.29
    • uniswapUniswap (UNI) $ 6.03
    • aptosAptos (APT) $ 5.52
    • daiDai (DAI) $ 1.00
    • nearNEAR Protocol (NEAR) $ 2.73
    • okbOKB (OKB) $ 52.85
    • susdssUSDS (SUSDS) $ 1.05
    • aaveAave (AAVE) $ 205.05
    • ondo-financeOndo (ONDO) $ 0.966283
    • blackrock-usd-institutional-digital-liquidity-fundBlackRock USD Institutional Digital Liquidity Fund (BUIDL) $ 1.00
    • ethereum-classicEthereum Classic (ETC) $ 18.45
    • crypto-com-chainCronos (CRO) $ 0.097663
    • internet-computerInternet Computer (ICP) $ 5.21
    • gatechain-tokenGate (GT) $ 21.73