DEV Community

Phil IPS
Phil IPS

Posted on

Openai Tutorial

Getting Started with OpenAI API via OpenRouter

If you want to experiment with OpenAI's powerful language models without dealing with their pricing or rate limits, OpenRouter is a great gateway. It aggregates multiple LLM providers and offers a single API endpoint.

Prerequisites

  • A free OpenRouter account (sign up at https://openrouter.ai)
  • An API key from your OpenRouter dashboard
  • Basic familiarity with HTTP requests (curl or Python)

Setting Up

First, obtain your API key. After logging in, navigate to the API keys section and copy the key.

Making a Request with curl

You can test the API directly from the command line:

curl -X POST https://api.openrouter.ai/v1/chat/completions \
  -H "Authorization: Bearer sk-your-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "google/gemma-2-9b-it",
    "messages": [{"role": "user", "content": "Explain quantum computing in simple terms."}]
  }'
Enter fullscreen mode Exit fullscreen mode

The response will be a JSON object containing the model's answer.

Example in Python

If you prefer Python, you can use the requests library:

import requests

API_URL = "https://api.openrouter.ai/v1/chat/completions"
API_KEY = "sk-your-key-here"

def call_openai(prompt):
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "model": "google/gemma-2-9b-it",
        "messages": [{"role": "user", "content": prompt}]
    }
    response = requests.post(API_URL, json=payload, headers=headers)
    response.raise_for_status()
    return response.json()["choices"][0]["message"]["content"]

# Example usage
answer = call_openai("What are the health benefits of meditation?")
print(answer)
Enter fullscreen mode Exit fullscreen mode

Tips & Tricks

  • Model Selection: OpenRouter supports many models (e.g., GPT‑4, Claude, Llama). Choose one that fits your use case and budget.
  • Rate Limits: Each model has its own rate limits. Check the docs for details.
  • Cost: OpenRouter's pricing is usage‑based. You’ll be billed in USDC based on token consumption.

Conclusion

OpenRouter provides a flexible way to access multiple LLMs through a single API. With just a few lines of code, you can prototype AI features for your apps. Experiment with different models and prompts to discover what works best for your project.

Happy hacking!

Top comments (0)