PROGRAM ZERO 18-month live AI, LLM & full-stack programme · ₹89,999 or ₹7,500/month · Starts 9 January 2027
Explore Program Zero →
Careers Ninza — business and startup leadership training
JOIN ZERO NINZA KIDS
JOIN ZERO NINZA KIDS
See all programs → Free live masterclass → Guides & articles → Newsletter →
Careers Ninza
AI & AUTOMATION 6 min read · Updated 27 October 2026

Claude API tutorial: a first Python script, choosing models, controlling cost and getting JSON back

The Claude API lets you put Claude inside your own scripts, apps and workflows. This tutorial covers getting an API key, a first Python call, system prompts, model choice, token costs, prompt caching, batch processing and reliable structured output.

CN
Careers Ninza AI faculty
Careers Ninza · Kolkata, India
Learn this live in our Claude AI Mastery Part 2 course

The Claude API lets your own code send messages to Claude and get responses back, so you can automate document processing, build assistants into apps or add AI steps to workflows. Start with an API key from the Claude Console, the official Python SDK, a clear system prompt and the smallest model that does the job well; then add prompt caching, batches and structured outputs as you scale.

The API is Level 7 of Claude AI Mastery Part 2, starting with session nine. This tutorial gives the essentials; always check the official API documentation for current models, parameters and prices.

How do you get started?

1Create an account in the Claude Console and add a small amount of credit.
2Create an API key and store it in an environment variable, never in your code or a shared file.
3Install the official SDK: pip install anthropic.
4Make a first call.
import os
import anthropic

client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

message = client.messages.create(
    model="<current-model-id>",   # pick from the models page in the docs
    max_tokens=500,
    system="You summarise business documents for Indian SME owners in plain English.",
    messages=[{"role": "user", "content": "Summarise this vendor contract in 5 bullet points: ..."}],
)
print(message.content[0].text)

The system prompt sets behaviour; the messages hold the conversation. Model IDs change as new versions release, so read the current list in the documentation.

How should you choose a model?

FamilyTypical use
HaikuFast, low-cost tasks at volume: classification, extraction, routing
SonnetBalanced quality and cost for most business tasks and coding
Opus, Fable and MythosHarder reasoning, complex analysis and demanding agent work, at higher cost

Test the smallest model that meets your quality bar on real examples. Many document and classification pipelines run well on smaller models.

How do tokens and costs work?

You pay per token for input (what you send) and output (what Claude writes), with different rates per model. A token is a piece of a word; English text averages roughly three to four characters per token, and Indian languages often use more tokens per word. Estimate cost by running a sample and reading the usage figures returned with each response.

—Prompt caching reduces cost and latency when you reuse the same long context (a policy manual, a codebase summary) across many calls.
—Message Batches process large numbers of requests asynchronously at a discount, ideal for overnight document jobs.
—Shorter outputs: ask for concise formats and set max_tokens sensibly.

How do you get reliable structured output?

For code that reads Claude’s answer, ask for JSON with a defined schema, or define a tool with an input schema and let Claude call it; the API also supports structured output features. Validate the result in code and retry or flag on failure.

prompt = """Extract fields from this invoice. Return only JSON:
{"supplier": str, "gstin": str|null, "invoice_no": str, "date": "YYYY-MM-DD", "total": number}
Invoice text: ..."""
# parse with json.loads(), validate types, and send failures to a review queue

Never put your API key in front-end code, a public repository or a shared spreadsheet. If a key leaks, revoke it in the Console immediately and create a new one. Set spending limits in the Console as a safety net.

Careers Ninza is an independent training institute. We are not affiliated with, sponsored by or endorsed by Anthropic, and our certificates are not Anthropic certifications. Claude is a trademark of Anthropic. Product features and plans change often; check claude.com for current details.

What can you build in the first weeks?

ProjectAPI features used
Folder summariser: read 200 PDFs and produce a summary sheetMessages, PDF input, batches
Email classifier for a support inboxSmall model, structured output
Invoice extractor with validationVision or PDF input, JSON, validation code
Policy Q&A with citationsLong context or retrieval, citations
Slack or WhatsApp assistantMessages, tool use, conversation history
Illustration: cost to summarise 1,000 two-page documents, relative scale
Large model, no batching100 (baseline)
Mid-size modelabout 35
Mid-size model with batchesabout 18

Source: Careers Ninza teaching illustration of relative cost; check current prices in the documentation.

What are the limits?

API outputs can be wrong like any model output, so production systems need validation, logging and human review for important decisions. Rate limits apply per account tier. Personal data sent to the API is processed by Anthropic under its terms; minimise it and follow India’s DPDP Act. And APIs change: pin model versions and test before upgrading.

What does a complete small project look like?

A worked example: a Kolkata freight forwarder receives 300 shipping documents a week by email and wants a daily summary of consignments, ports and expected dates. A simple Python project:

1A script downloads new PDF attachments from a dedicated mailbox.
2Each PDF is sent to Claude with a prompt asking for consignee, port of loading and discharge, container numbers and ETA as JSON.
3The script validates the JSON (container number formats, dates) and writes rows to a Google Sheet.
4Rows failing validation are marked for review by an operations executive.
5At 6 pm, a summary of the day’s consignments is emailed to the team.

This uses only the Messages API, PDF input, structured output and basic Python. It runs on a small server or scheduled job, and with Claude Code helping write it, a non-developer who completed Part 1 can build it in Part 2.

How should errors and retries be handled?

—Wrap API calls in retries with backoff for temporary errors and rate limits.
—Log every request ID, input reference and output for debugging.
—Set timeouts so a stuck call does not block the whole job.
—Send failures to a review list rather than silently skipping them.

Where do tools, MCP and agents fit?

Once simple calls work, tool use lets Claude call your functions (look up a customer, check stock), MCP lets you connect Claude to systems through a standard protocol, and the Claude Agent SDK provides a framework for agents that plan and act over several steps. Our posts on MCP and the Agent SDK cover these next steps, which make up the later sessions of Part 2.

KEY TAKEAWAYS

—Keep your API key in an environment variable and set spending limits.
—Start with the smallest model that meets your quality bar.
—Use prompt caching and batches to cut cost at scale.
—Get structured output with schemas or tools, then validate in code.
—Add retries, logging and review queues before production use.

Our Claude AI Mastery Part 2 batches run live online, so the same class reaches learners and business owners in metros such as Delhi NCR, Mumbai, Hyderabad, Chennai and Kolkata, growing cities such as Patna, Bhopal, Visakhapatnam, Chandigarh and Ranchi, and smaller industrial towns such as Moradabad, Erode, Bhilwara, Siliguri and Jamshedpur, at the same fee. Each city page explains how local businesses use Claude API, for example in Patna, Moradabad, Jamshedpur.

Learn this live: Claude AI Mastery Part 2

Use the Claude API with tools, structured outputs, retrieval, MCP and agents, and ship a deployed capstone. 30 live hours, ₹29,999, after Part 1.

SHORT-TERM COURSE · LIVE ONLINE
Claude AI Mastery Part 2

Build, deploy and maintain software, automations and agents with Claude Code, the Claude API and MCP. Levels 6 and 7, for developers and ambitious non-programmers who have completed Part 1.

₹29,999 · single payment30 hoursLive, mentor-ledCertificate on completion

Frequently asked questions

How do I get a Claude API key?+

Create an account in the Claude Console, add credit, and generate an API key. Store it in an environment variable and never share it or put it in front-end code.

How much does the Claude API cost?+

You pay per input and output token, with different rates per model. Prompt caching and batch processing can reduce costs. Check the current pricing page and estimate with a sample run.

Which Claude model should I use with the API?+

Use the smallest model that meets your quality bar: Haiku for fast, high-volume tasks; Sonnet for most business tasks; Opus, Fable or Mythos for harder reasoning. Test on real examples.

How do I get JSON output from Claude?+

Ask for JSON with a defined schema, or define a tool with an input schema for Claude to call, or use the API’s structured output features. Validate the result in your code.

Can the Claude API read PDFs and images?+

Yes. The API accepts images and PDF documents as input, which is useful for invoices, forms and reports.

Where can I learn the Claude API in India?+

Careers Ninza Claude AI Mastery Part 2 covers the Claude Platform and API, tools, structured outputs, retrieval, MCP and agents over 30 live hours for ₹29,999, after Part 1.

Related reading

AI & AUTOMATION Rolling Out Claude Across an Indian Company: Pilots, Governance, Training and ROI Buying licences is the easy part of an AI rollout. This guide covers how Indian companies should pilot Claude, set governance and data rules, train people by role, build shared Skills and connectors, control cost and measure real value. 6 min read AI & AUTOMATION AI Automation for HR and Recruitment: Screening, Onboarding and Employee Questions HR teams spend hours on repetitive tasks: sorting CVs, scheduling interviews, onboarding paperwork and answering the same policy questions. This guide shows practical AI automations for Indian HR teams, with fairness and privacy safeguards. 6 min read AI & AUTOMATION Claude for Small Business Owners in India: 20 Practical Uses That Save Time and Money Owners of Indian MSMEs wear every hat: sales, accounts, HR, marketing and operations. This guide lists 20 practical ways Claude helps, from quotations and GST-ready summaries to job descriptions and customer replies, with safety rules and a plan to start. 6 min read

We teach this, live

Every article here comes from something we teach. Sit in on a free masterclass and judge the mentors yourself.