Jay Rocco is the Founder and Editor of FullStack Alpha. He has tested 200+ AI stock tools since 2022 and run 15+ AI trading platforms on live accounts with his own money. He reviews the software. He does not tell you what stocks to buy.
Alpaca API keys are a key ID and secret pair you generate for free in the Alpaca dashboard, one pair per account, and send with every request in the APCA-API-KEY-ID and APCA-API-SECRET-KEY headers. Paper keys work only on the paper host and live keys only on the live host, so a mismatch fails every call. Keep the secret in a private .env file or a secret manager, test it with a read-only call to /v2/account, and regenerate the pair the moment it leaks. A 401 almost always means a wrong, revoked or mismatched key; a 403 on an order usually means buying power, not a broken key. 14
Start with paper credentials. A working connection should not become an expensive security experiment. This tutorial is part of the broker setup series at AI Stock Trading Bots, and if you have never placed an order through code, read Alpaca API for beginners first. 9
The Short Version
- Alpaca API keys cost $0 to generate; paid market data feeds are a separate question. 4
- Paper and live environments require separate credentials, and a new paper account needs a new pair. 5
- Python scripts should receive secrets through private runtime configuration, never hard coded. 9
- GitHub repositories must never contain working credentials. 9
- Regenerating a key means updating every connected application, including an MCP config file. 4
- Authentication does not automatically grant every product or feed entitlement. 2
If Your Key Leaks: The 5 Step Response
Pause new order submissions before you touch anything else.
Create new keys in the dashboard. The old secret stops working.
Review open orders, positions and recent activity for anything you did not place.
Swap the new keys into each deployment, then restart and test with a read request.
Scrub GitHub history, logs and screenshots. Deleting a .env file does not revoke access.
Bookmark this. You will not want to read a long guide while a stranger has access to your account.
What Are Alpaca Credentials, and What Can They Reach?
Alpaca credentials identify and authenticate software making requests to its APIs. The Trading API connects a personal bot to account information and order execution; the Market Data API supplies prices under separate feed entitlements. 4 6
Each key ID comes with a private secret. REST requests send them through the APCA-API-KEY-ID and APCA-API-SECRET-KEY headers, never through a public webpage or a shared prompt. 8 Alpaca also accepts the same pair as HTTP Basic credentials, with the key ID as the username and the secret as the password. 14
Treat the pair like a house key. Alpaca’s authentication guide names two headers, one for the key ID and one for the secret, and anyone holding both can read your account and trade in it. Guard them the way you guard your brokerage password. 14
Trading data, market data, and broker access
Trading API data includes positions, balances, and orders. Alpaca data products include historical and real-time prices, with coverage that depends on your feed. Check crypto and options access separately, and if options are the plan, read our Alpaca options API guide before you request approval. 6
The Broker API is for businesses building brokerage apps, and it uses different hosts and a newer client credentials token flow. A first-time personal bot builder needs the Trading API. Review the Alpaca directory profile before choosing surrounding software, and see how Alpaca stacks up against other brokers that let a bot place real orders. 14
How Do You Generate Alpaca API Keys?
Generate alpaca api keys inside the Alpaca dashboard after selecting Paper Trading or your live brokerage account. Copy the secret into private storage the moment it is shown, and pair the credentials with that environment’s base URL. 4
- Sign in through Alpaca’s official site. The paper dashboard lives at app.alpaca.markets/paper/dashboard/overview.
- Select Paper Trading for development.
- Open API Keys and select Generate New Keys.
- Save the key ID and secret in a password manager or private .env file.
- Make a read request before enabling orders. 4 5
Your keys belong in your deployment configuration. They do not belong in screenshots, support posts, AI chats, or GitHub issues. 9
One trap catches people who experiment a lot. Alpaca’s dashboard now lets you open and delete paper accounts instead of resetting them, and its docs say to generate new keys for any newly created account. If your old paper alpaca api keys suddenly return errors after you opened a fresh paper account, that is why. 5
How do authentication permissions work?
Successful authentication proves Alpaca accepted the credentials. It does not prove the account has options approval, crypto eligibility, margin, or access to a particular market data feed. Check product permissions before enabling execution. 2
A denied data request often means a subscription mismatch, not a bad key. Read the error before regenerating anything. 3
Paper and live never mix. Alpaca runs paper and live as two separate environments, each with its own pair of keys. Its authentication guide says plainly that live credentials do not work on the paper API, or the other way around. 14
How Do You Test Alpaca API Keys With curl?
The fastest test of alpaca api keys is one GET request to the account endpoint. It reads balances and status and cannot place an order. Alpaca’s own authentication example uses this exact endpoint. 14 10
Load the keys into your shell from the .env file first, so the secret never sits in your command history:
set -a; source .env; set +a # loads APCA_API_KEY_ID and APCA_API_SECRET_KEY
curl -s -w "\nHTTP %{http_code}\n" \
https://paper-api.alpaca.markets/v2/account \
-H "APCA-API-KEY-ID: $APCA_API_KEY_ID" \
-H "APCA-API-SECRET-KEY: $APCA_API_SECRET_KEY"
A healthy response is HTTP 200 and a JSON object with fields such as status, buying_power, cash, trading_blocked and options_approved_level. If status reads ACTIVE and trading_blocked is false, the keys and host match. 10
For a live account, swap the host to api.alpaca.markets and use the live pair. Do not change anything else. Every Trading API response also carries an X-Request-ID header; Alpaca asks you to include it in support tickets, so log it next to failed calls. 11
401 vs 403: Why Are Your Alpaca API Keys Rejected?
When we tested in 2026, a request to either trading host with a missing or fake key came back as HTTP 401 with the body {"message": "unauthorized."}, and the market data host answered with a plain 401 page. Alpaca’s older doc examples show the same mistake as a 403, so read the response body, not just the code. 11 2
| What you see | Usual cause | First fix |
|---|---|---|
401 unauthorized. on a trading host | Key missing, mistyped, regenerated, or a paper key sent to the live host | Check both header names, copy the pair again, confirm the host matches the account |
| 401 after opening a new paper account | Old keys belong to the old paper account | Generate new keys for the new account 5 |
| 403 on market data | Not authenticated, wrong credentials, or insufficient permissions | Use data.alpaca.markets, recheck the key pair 2 |
403 with subscription does not permit querying recent SIP data | Free plan asking for SIP trades or quotes from the last 15 minutes | Request feed=iex, or pay for Algo Trader Plus 2 |
| 403 when submitting an order | Buying power or shares not sufficient | Read buying_power and your position size before retrying 12 |
| 422 when submitting an order | Input parameters not recognized | Fix the order payload; the keys are fine 12 |
The decision rule is short. A 401 is a key or host problem, so fix credentials. A 403 on an order is an account problem, so regenerating keys will not help and only creates more config to update.
The SIP row matters if you pay attention to cost. Whether $99 a month for the full feed is worth it is a separate call, covered in our Alpaca API pricing breakdown.
How Should You Store Alpaca API Keys Safely?
Store alpaca api keys in a secret manager in production, or a private local .env file during development. Keep that file out of version control, restrict who can read it, and load secrets only into the process that needs them. 9
Paper versus live: choose the correct base URL
| Environment | Base URL | Create in | Risk | Safe practice |
|---|---|---|---|---|
| Paper | https://paper-api.alpaca.markets | Paper dashboard | Simulated execution | Development only |
| Live | https://api.alpaca.markets | Live dashboard | Real money | Separate deployment secrets |
These trading hosts are different from Alpaca’s market data host, data.alpaca.markets, which serves both paper and live accounts. Copy the right endpoint from Alpaca’s documentation. 14 3
Environment files and GitHub
Add .env and any credential files to .gitignore before you create them. An ignore rule cannot remove a secret already committed to GitHub history. If a key was committed, replace it first, then clean the repository history. 9
Keep placeholders in a .env.example file. Environment variables reduce accidental exposure in source code, but logs, crash reports, shared notebooks, and compromised machines can still leak them. Never paste secrets into an AI chat. 9
Local storage checkpoint: Alpaca’s CLI documentation describes profile files protected with 0600 permissions, meaning only the owner can read or write them. File permissions do not replace production secret management. 1
Python example: a safe first connection
Install alpaca-py and python-dotenv in a private Python environment. This example only reads your account and open orders; it does not submit anything. The explicit paper=True keeps the client pointed at paper trading. 5
import os
from dotenv import load_dotenv
from alpaca.trading.client import TradingClient
load_dotenv() # reads APCA_API_KEY_ID and APCA_API_SECRET_KEY from .env
client = TradingClient(
os.environ["APCA_API_KEY_ID"],
os.environ["APCA_API_SECRET_KEY"],
paper=True,
)
account = client.get_account()
print("Status:", account.status, "| Buying power:", account.buying_power)
print("Open orders:", len(client.get_orders()))
If this prints your paper account status, your keys, base URL and permissions are wired correctly. Only then write order logic. Install alpaca-py from the official package, not a random GitHub attachment.
How Do You Use Alpaca API Keys With the Alpaca MCP Server?
The official Alpaca MCP Server lets an AI client such as Claude Desktop, Claude Code, Cursor or VS Code read your account and place orders by calling Alpaca’s APIs with your alpaca api keys. It is open source at github.com/alpacahq/alpaca-mcp-server, and the current V2 rewrite is version 2.4.0. Alpaca’s docs page lists 65 tools while the GitHub README lists 72, so expect the count to move between releases. 13
What you need, per Alpaca’s setup page:
- Python 3.10 or newer and uv, because the server launches with
uvx alpaca-mcp-server. - Paper keys from the paper dashboard. Alpaca says a free paper account is enough to start.
- Two environment variables in the client config:
ALPACA_API_KEYandALPACA_SECRET_KEY. 13
Watch the names. The MCP server reads ALPACA_API_KEY and ALPACA_SECRET_KEY, while the Python SDK example above reads APCA_API_KEY_ID and APCA_API_SECRET_KEY. Paste the right pair under the right names, or the server will start and then fail on its first call. 13
Two settings decide how much damage a confused AI can do:
ALPACA_PAPER_TRADEdefaults totrue. Leave it there. Setting it tofalsesends orders to your live account.ALPACA_TOOLSETSlimits which tools load. Leave outtradingand the assistant can read balances, data and news but cannot place or cancel orders. Toolsets include account, trading, watchlists, assets, stock-data, crypto-data, options-data, corporate-actions, news and fixed-income-data, plus locates, which do not work in paper trading. 13
The catch is storage. The MCP config file (for example claude_desktop_config.json) holds your secret in plain text. Keep it out of synced dotfile repos, and add it to your rotation list so step 04 of the leak response covers it. Before you let any assistant trade, read our piece on AI trading agent risks and the external kill switch.
Who Needs Alpaca API Keys: Day Traders, Swing Traders, or Bot Builders?

Alpaca fits developers who want programmatic research and execution through a broker connection. A day trader or swing trader can benefit from automation; a long-term investor may need only scheduled reporting, while a scalper must test latency and execution limits separately. 4
Keys solve connectivity, not strategy quality. Position sizing decides how much capital you expose. A stop loss is an exit instruction, not protection against stolen credentials.
Start with the retail AI trading guide, then check your strategy’s math with the trading expectancy calculator.
Backtest with market data: know the limits
Free access does not mean every exchange feed is included. The free plan streams the IEX feed; the full SIP consolidated feed is paid. Paper execution also cannot reproduce every live fill: Alpaca’s paper engine does not check your size against the quoted liquidity, does not simulate dividends, and randomly partial-fills about 10% of eligible orders. These are practical limits, not footnotes. 2 5
A working connection says nothing about profitability. Keep research tools separate from broker permissions; the swing trading tools directory helps compare research workflows.
Check which Alpaca entity provides each service
Brokerage custody, securities clearing, and crypto services carry different terms. Do not assume securities protections like SIPC cover crypto. Read the Alpaca Crypto LLC terms separately if your bot trades crypto.
Top 5 Alpaca API Key Safety Habits

Apply these habits before your keys ever reach live execution.
- Environment isolation: keep paper and live deployments separate. 5
- Private runtime injection: load secrets outside source files. 9
- Minimal logging: redact authentication headers and sensitive responses, but keep the
X-Request-ID. 9 - Controlled regeneration: keep a list of every app that uses the key, AI clients included. 4
- Read-first validation: confirm environment and access with the account call before enabling orders. 8
How Does Alpaca Compare to Other Broker Connections?
Pick a broker around your existing account, the products you need, and how you deploy. Alpaca is the most direct entry point for a personal bot, but the key setup should not decide your whole broker choice. 4
Interactive Brokers makes sense for global markets and futures. Tradier suits options bots. TradeStation suits traders already on its platform, and Schwab suits existing Schwab customers. Check each broker’s current developer terms rather than assuming the rules match. Our Alpaca review covers the broker side in more depth.
Prefer less code? Read the Composer bot-building review. A visual builder still needs permission controls.
When and How Should You Rotate Alpaca API Keys?
Rotate alpaca api keys immediately after any suspected exposure, and review them whenever someone’s access to your deployment changes. Keep your own review schedule; Alpaca does not mandate one. 9
How do you revoke compromised credentials?
Stop affected automation, regenerate the credentials in the dashboard, and update trusted deployments. Contact Alpaca support if you cannot invalidate the exposed key. Deleting a local .env file does not revoke server access. 4 9
Inspect recent activity, open orders, and positions. Rotation does not close positions or cancel existing orders. Keep evidence without copying the secret into a support ticket.
Can you rotate without stopping trades?
Do not assume Alpaca supports two active personal keys at once. Pause new submissions, reconcile outstanding orders, replace the secret, restart clients, and verify access before resuming. 4
A timeout during an order submission is not proof of rejection. Check the broker’s order state before retrying, or your recovery can create a duplicate position.
Can multiple apps or strategies share one key?
They can, but shared access increases the damage one compromised app can cause. List every app using the key, isolate strategy processes, and rotate the moment any one of them is exposed. 9
Can you set expiration dates?
Do not assume personal keys have configurable expiration dates. If the dashboard does not offer one, put a review date in your own deployment notes. A calendar reminder alone does not revoke anything. 9
Our Take
Generate paper credentials, secure the local configuration, and make a read request before enabling execution. Practice the leak response above while no real money is exposed. Your alpaca api keys should have a recovery plan before they have live access. 5
FullStack Alpha’s rule is simple: systems over hacks. Write down your safeguards now, then write down who can access the secret.
Compare the tools that sit on top of a broker connection in the FullStack Alpha directory of 200+ AI stock tools.
References
The Alpaca documentation below supports the connection and security guidance. Documentation changes; check the current page before deploying.
- Alpacas Cli
- Market Data Faq
- Getting Started With Alpaca Market Data
- Connect To Alpaca Api
- Paper Trading
- About Market Data Api
- Authentication 1
- Api Key Security Best Practices For Alpaca Builders
- Get Account (API reference)
- Getting Started With Trading API
- Create an Order (API reference)
- Trading API MCP
- Authentication
Affiliate disclosure: FullStack Alpha may earn a commission from qualifying purchases through affiliate links.
By Jay Rocco, Founder and Editor, FullStack Alpha.
Stay alpha.
Frequently Asked Questions
How to get Alpaca free API key?
Create an Alpaca login, select the paper environment, and generate credentials in the dashboard’s credential panel. Store the secret privately when displayed. Paper access lets you develop without funding live execution. Free credentials do not include every paid market feed or waive charges associated with live activity. [4](https://alpaca.markets/learn/connect-to-alpaca-api)
Can I get API Keys for free?
Yes. Alpaca does not charge a separate fee merely to generate personal credentials. That answers “Is Alpaca API free?” only at the authentication level. Alpaca API pricing and Alpaca pricing searches may also refer to subscriptions or transaction-related costs, which are separate from generating credentials. [4](https://alpaca.markets/learn/connect-to-alpaca-api) [2](https://docs.alpaca.markets/us/docs/market-data-faq)
What is Alpaca API?
Alpaca provides programmatic interfaces for brokerage functions and price information. Developers can retrieve positions, inspect balances, and submit supported transactions through authenticated software. Its personal execution interface differs from the Broker API used for brokerage applications. Beginners should start with simulation and read requests rather than live submissions. [4](https://alpaca.markets/learn/connect-to-alpaca-api)
How to find Alpaca secret key?
Look where you securely saved the secret when generating credentials. If it is no longer available, generate a replacement through the dashboard rather than searching public repositories or attempting recovery from screenshots. Update every connected deployment afterward. Never send the secret to someone offering troubleshooting help. [4](https://alpaca.markets/learn/connect-to-alpaca-api) [9](https://alpaca.markets/learn/api-key-security-best-practices-for-alpaca-builders)
What are common mistakes with alpaca api keys?
Common mistakes include committing secrets, mixing environments, logging authentication headers, and assuming successful authentication permits every feed. Searches such as “Alpaca api keys github” or “Alpaca api keys reddit” should lead to examples and discussion, never credentials to borrow. Consult Alpaca API documentation for authentication and entitlement rules. [9](https://alpaca.markets/learn/api-key-security-best-practices-for-alpaca-builders)
What is the safest way to pass credentials to a bot?
Supply credentials through a managed secret store or private process environment. For local development, a protected `.env` file can work if your application explicitly loads it. Python and alpaca-py do not make arbitrary configuration names automatic. Verify your loader, redact logs, and keep secrets out of command history. [9](https://alpaca.markets/learn/api-key-security-best-practices-for-alpaca-builders)
Jay Rocco is the Founder and Editor of FullStack Alpha. He has tested 200+ AI stock tools since 2022 and run 15+ AI trading platforms on live accounts with his own money. He reviews the software. He does not tell you what stocks to buy.