Loading

1. What Is an API?

Imagine you're at a restaurant. You don't go into the kitchen to cook your own food — you tell the waiter what you want, the waiter goes to the kitchen, and brings back what you ordered. You never see the kitchen, you don't need to know how the food is made. You just interact with the waiter.

An API (Application Programming Interface) is that waiter. In this case, you are your Python code, the waiter is the Claude API, and the kitchen is Claude (the AI model running on Anthropic's servers). Your code sends a request to the API — a message, a question, a task — and the API returns Claude's response. You never need to run Claude yourself or understand how it works internally.

This is incredibly powerful. Instead of building an AI from scratch (which requires massive compute and data), you can add Claude's full intelligence to your own application with just a few lines of Python. You can build a study tool, a code assistant, a customer service bot, a data analyser — anything that needs language understanding.

What the Claude API Lets You Do

Call Claude from your own Python code. Send messages programmatically. Get responses you can process, format, save, or display however you like. Build AI-powered tools tailored to your specific use case — with you in control of the prompts, the context, and the output format.

2. Setting Up

Setting up takes about 5 minutes. Here's exactly what to do, step by step.

Step 1 — Get Your API Key

  1. Go to console.anthropic.com in your browser
  2. Click "Sign Up" — use your email to create an account (a Gmail works fine)
  3. Once logged in, click your profile icon in the top right, then "API Keys"
  4. Click "Create Key" — give it a name like "my-first-project"
  5. Copy the key that appears. It starts with sk-ant-. This is shown only once — save it immediately
Security Warning

Never paste your API key directly into your Python code, especially if you'll share the file or push it to GitHub. If someone gets your key, they can use your account and run up charges. Always store it as an environment variable. We'll show you how below.

Step 2 — Install the Python Library

Open your terminal (Command Prompt, PowerShell, or VS Code terminal) and run:

Terminal
pip install anthropic

Step 3 — Set Your API Key as an Environment Variable

This keeps your key out of your code files. Do this once in your terminal before running your scripts:

On Windows (Command Prompt)
set ANTHROPIC_API_KEY=sk-ant-your-actual-key-here
On Mac / Linux
export ANTHROPIC_API_KEY=sk-ant-your-actual-key-here

For a permanent setup, add this line to your .env file and use the python-dotenv library to load it. But for learning, the terminal command above is enough.

Python — import and create the client
import anthropic
import os

# The client automatically reads ANTHROPIC_API_KEY from the environment
client = anthropic.Anthropic()

print("Client ready.")   # If this runs without error, you're set up.

3. Your First API Call

Let's send a message to Claude and print the response. This is the core of everything — once you understand this pattern, you can build anything.

The Messages Format

Claude uses a conversation-style format. Every message you send has two parts:

  • role — either "user" (you) or "assistant" (Claude)
  • content — the actual text of the message

You pass a list of messages. For a single question, you pass one message with role: "user". Claude's reply comes back as the assistant message.

Python — your first complete API call
import anthropic

client = anthropic.Anthropic()   # reads API key from environment

# Send a message to Claude
response = client.messages.create(
    model="claude-opus-4-5",     # the model to use
    max_tokens=1024,             # maximum length of the reply
    messages=[
        {
            "role": "user",
            "content": "What is PWM and how is it used to control motor speed?"
        }
    ]
)

# Read the response
answer = response.content[0].text
print(answer)

Reading the Response

The response object has several fields, but the one you need most is response.content[0].text. This is Claude's reply as a plain string that you can print, save, process, or display.

Why [0]?

response.content is a list — in most cases it contains one item, a text block. Accessing [0] gets that first (and usually only) item. Then .text extracts the actual string.

4. System Prompts — Giving Claude a Role

A system prompt is a set of instructions that Claude follows for the entire conversation. It's separate from your message — it shapes Claude's personality, expertise level, format preferences, and constraints before the conversation even starts.

This is the difference between a general-purpose AI and a specialised tool. With the right system prompt, Claude becomes your dedicated tutor, your code reviewer, your report editor, or your technical advisor — and it maintains that role consistently throughout the session.

Python — using a system prompt to create a specialised assistant
import anthropic

client = anthropic.Anthropic()

response = client.messages.create(
    model="claude-opus-4-5",
    max_tokens=1024,
    system=(
        "You are a helpful tutor for engineering students in Kerala, India. "
        "You explain technical concepts in simple, clear English with practical "
        "examples relevant to Indian engineering colleges. "
        "When explaining hardware concepts, relate them to common components "
        "like Arduino, ESP32, and basic electronics available in India. "
        "Keep answers concise and structured with bullet points where appropriate."
    ),
    messages=[
        {
            "role": "user",
            "content": "Explain the I2C protocol. I'm a 2nd year ECE student."
        }
    ]
)

print(response.content[0].text)

Run this and compare the output to the same question without the system prompt. The difference is significant — with the system prompt, Claude knows who it's talking to, adjusts its vocabulary, and gives a more targeted answer.

What Good System Prompts Do

  • Set the expertise level and communication style
  • Specify the format of answers (bullet points, numbered steps, code blocks)
  • Restrict the topic area (so Claude stays on-task)
  • Establish context that applies to every message in the session
  • Give Claude a "persona" that makes your app feel like a specialised product

5. Build a Study Helper App

Let's put it all together. This is a complete, working command-line study assistant. You give it a topic, it generates well-structured study notes. This is the kind of practical AI tool you can build and actually use.

Python — study_helper.py (complete working application)
"""
Study Helper — powered by Claude API
Generates structured study notes for any engineering topic.
Run: python study_helper.py
"""

import anthropic
import sys

SYSTEM_PROMPT = """You are an expert study note generator for engineering students
in India, specialising in ECE, EEE, CSE, and Mechanical Engineering topics.

When given a topic, generate study notes in exactly this format:

TOPIC: [topic name in caps]

KEY CONCEPTS (5 bullet points, one sentence each):
- ...
- ...
- ...
- ...
- ...

HOW IT WORKS (2-3 sentences, plain language, one good analogy):
...

FORMULA / KEY VALUES (if applicable):
...

COMMON EXAM QUESTIONS:
1. [Question] — [Short answer]
2. [Question] — [Short answer]
3. [Question] — [Short answer]

REMEMBER THIS: [One memorable summary sentence]

Keep the entire response under 400 words. Use simple language."""


def generate_study_notes(topic: str) -> str:
    """Call Claude and return formatted study notes for the given topic."""
    client = anthropic.Anthropic()

    try:
        response = client.messages.create(
            model="claude-opus-4-5",
            max_tokens=1024,
            system=SYSTEM_PROMPT,
            messages=[
                {
                    "role": "user",
                    "content": f"Generate study notes for: {topic}"
                }
            ]
        )
        return response.content[0].text

    except anthropic.AuthenticationError:
        return "Error: Invalid API key. Check your ANTHROPIC_API_KEY environment variable."
    except anthropic.RateLimitError:
        return "Error: Rate limit reached. Wait a minute and try again."
    except Exception as e:
        return f"Unexpected error: {e}"


def main():
    print("\n" + "=" * 50)
    print("  QUADRATECH STUDY HELPER — Powered by Claude")
    print("=" * 50)
    print("Type a topic to get study notes. Type 'quit' to exit.\n")

    while True:
        topic = input("Topic: ").strip()

        if not topic:
            continue
        if topic.lower() in ('quit', 'exit', 'q'):
            print("Goodbye!")
            break

        print("\nGenerating notes...\n")
        notes = generate_study_notes(topic)
        print(notes)
        print("\n" + "-" * 50 + "\n")


if __name__ == "__main__":
    main()

How to Run It

  1. Save the code above as study_helper.py
  2. Set your API key: set ANTHROPIC_API_KEY=sk-ant-...
  3. Run: python study_helper.py
  4. Type any topic — "UART protocol", "PID control", "Python decorators", "BJT transistor"
Try It Yourself

Extend the app with a second mode. After showing the notes, ask the user: "Want 5 quiz questions on this topic? (y/n)". If they say yes, make a second API call with a different prompt: "Give me 5 multiple choice quiz questions on [topic] with answers hidden — show answers only after all 5 questions." This is a complete study session tool.

API Access at the Quadratech Internship

During the 10-day internship program at Quadratech, students in the AI track get full API access to Claude and Gemini to build real AI-powered projects — with mentor support, Fab Lab tools, and a co-branded certificate. The program fee covers the API credits, so you don't need to pay separately. This is the fastest way to go from these basics to building something genuinely impressive in your portfolio.