0% found this document useful (0 votes)
2 views13 pages

Python Ai API

The document is a practical guide for building AI applications using Python and APIs, covering essential topics from Python basics to API fundamentals. It includes instructions on setting up environments, calling APIs, handling JSON, and building a simple FastAPI service. The guide is aimed at learners with no prior web or API experience, emphasizing the integration of AI features through structured programming practices.

Uploaded by

mariyajemi710
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views13 pages

Python Ai API

The document is a practical guide for building AI applications using Python and APIs, covering essential topics from Python basics to API fundamentals. It includes instructions on setting up environments, calling APIs, handling JSON, and building a simple FastAPI service. The guide is aimed at learners with no prior web or API experience, emphasizing the integration of AI features through structured programming practices.

Uploaded by

mariyajemi710
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python & API Basics for AI Apps

A Practical Guide from Basic to Intermediate

Building the foundations you need to call models, wrap tools, and ship AI features

Developed by Cyber Wolf

Developed by Cyber Wolf

July 21, 2026

Contents
1 Introduction 3

2 Python Essentials for AI Work 3


2.1 Environment and packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.2 Data types you will use constantly . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.3 Functions, type hints, and errors . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.4 JSON in Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

3 What Is an API? 5
3.1 HTTP methods you need . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.2 Status codes (quick map) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
3.3 Headers that matter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

4 Calling APIs from Python 6


4.1 Synchronous requests with requests . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.2 Async requests with httpx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
4.3 Official SDKs vs raw HTTP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

5 Core Patterns in AI APIs 7


5.1 Chat messages and roles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
5.2 Embeddings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
5.3 Streaming responses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
5.4 Retries and backoff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

6 Validating Data with Pydantic 9

7 Building Your Own API with FastAPI 9


7.1 Minimal chat endpoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

8 Intermediate: Tools / Function Calling 10

9 Security and Production Checklist 12

10 Mini Project: Prompt → API → Answer 12

1
Python & API Basics for AI Apps Cyber Wolf

11 Practice Exercises 13

12 Quick Reference 13

Developed by Cyber Wolf 2 Basic → Intermediate


Python & API Basics for AI Apps Cyber Wolf

1 Introduction
Modern AI applications are rarely “just a model.” They are Python programs that:
• call remote APIs (OpenAI, Anthropic, Hugging Face, custom backends),
• send and receive structured JSON,
• manage keys and rate limits,
• and often expose their own HTTP endpoints for frontends or other services.
This document takes you from Python basics through HTTP/API fundamentals to
practical patterns used in AI apps—streaming, retries, function calling, and a small FastAPI
service.
Note
You should already know how to open a terminal and install Python 3.10+. No prior web
or API experience is required.

2 Python Essentials for AI Work


2.1 Environment and packages
Always isolate project dependencies:
1 # Create and activate a virtual environment
2 python -m venv . venv
3
4 # Windows ( PowerShell )
5 .\. venv \ Scripts \ Activate . ps1
6

7 # macOS / Linux
8 source . venv / bin / activate
9
10 # Install common AI / API libraries
11 pip install requests httpx python - dotenv openai fastapi uvicorn
pydantic

Keep secrets out of source code with a .env file:


1 # . env ( never commit this file )
2 OPENAI_API_KEY = sk -...
3 AN THROPI C_API_ KEY = sk - ant -...

Load them in Python:


1 from dotenv import load_dotenv
2 import os
3

4 load_dotenv ()
5 api_key = os . getenv ( " OPENAI_API_KEY " )
6 if not api_key :
7 raise RuntimeError ( " OPENAI_API_KEY is missing " )

Developed by Cyber Wolf 3 Basic → Intermediate


Python & API Basics for AI Apps Cyber Wolf

2.2 Data types you will use constantly


AI APIs speak in strings, lists, and dictionaries (JSON objects).
1 # Strings and f - strings
2 name = " Ada "
3 prompt = f " Explain APIs to { name } in one sentence . "
4
5 # Lists ( ordered collections )
6 messages = [
7 { " role " : " system " , " content " : " You are a helpful tutor . " } ,
8 { " role " : " user " , " content " : prompt } ,
9 ]
10
11 # Dictionaries ( key - value maps )
12 payload = {
13 " model " : " gpt -4 o - mini " ,
14 " messages " : messages ,
15 " temperature " : 0.2 ,
16 }
17
18 # Unpack safely
19 model = payload . get ( " model " , " unknown " )
20 print ( model )

2.3 Functions, type hints, and errors


Type hints make API code easier to read and catch mistakes early.
1 from typing import Any
2
3 def b ui ld _c ha t_ pa yl oa d (
4 user_text : str ,
5 model : str = " gpt -4 o - mini " ,
6 temperature : float = 0.2 ,
7 ) -> dict [ str , Any ]:
8 return {
9 " model " : model ,
10 " messages " : [{ " role " : " user " , " content " : user_text }] ,
11 " temperature " : temperature ,
12 }
13
14 try :
15 payload = bui ld _c ha t_ pa yl oa d ( " What is an API ? " )
16 except TypeError as exc :
17 print ( " Bad arguments : " , exc )

Tip

Prefer raising clear exceptions (ValueError, RuntimeError) when required config is


missing. Silent None values are a common source of confusing API failures.

2.4 JSON in Python


JSON is the lingua franca of APIs. Python’s json module converts between text and Python
objects.

Developed by Cyber Wolf 4 Basic → Intermediate


Python & API Basics for AI Apps Cyber Wolf

1 import json
2
3 data = { " prompt " : " Summarize this . " , " max_tokens " : 128}
4 text = json . dumps ( data ) # Python dict -> JSON string
5 back = json . loads ( text ) # JSON string -> Python dict
6
7 # Pretty - print for debugging
8 print ( json . dumps ( back , indent =2) )

JSON Python Notes


object {} dict keys must be strings in JSON
array [] list ordered
string str UTF-8
number int/float no separate int/float in JSON
true/false True/False capitalization differs
null None

3 What Is an API?
An API (Application Programming Interface) is a contract: how one program asks another
program to do work and how the answer looks.
For AI apps, the common style is a REST API over HTTP:
1. Your code sends an HTTP request (method + URL + headers + optional body).
2. The server runs the model or business logic.
3. The server returns an HTTP response (status code + headers + body, often JSON).

3.1 HTTP methods you need

Method Typical use In AI apps


GET Read data Fetch job status, list models
POST Create / run action Chat completions, embeddings
PUT/PATCH Update Update conversation metadata
DELETE Remove Delete a stored file or thread

Most model inference calls are POST requests with a JSON body.

3.2 Status codes (quick map)


• 2xx — success (200 OK, 201 Created)
• 4xx — client error (400 bad request, 401 unauthorized, 429 rate limited)
• 5xx — server error (500, 503)

Caution
Treat 401/403 as configuration bugs (bad or missing API key). Treat 429 as temporary:
backoff and retry.

Developed by Cyber Wolf 5 Basic → Intermediate


Python & API Basics for AI Apps Cyber Wolf

3.3 Headers that matter


1 {
2 " Authorization " : " Bearer sk -... " ,
3 " Content - Type " : " application / json " ,
4 " Accept " : " application / json "
5 }

4 Calling APIs from Python


4.1 Synchronous requests with requests
1 import os
2 import requests
3 from dotenv import load_dotenv
4
5 load_dotenv ()
6
7 url = " https :// api . openai . com / v1 / chat / completions "
8 headers = {
9 " Authorization " : f " Bearer { os . getenv ( ’ OPENAI_API_KEY ’) } " ,
10 " Content - Type " : " application / json " ,
11 }
12 body = {
13 " model " : " gpt -4 o - mini " ,
14 " messages " : [
15 { " role " : " user " , " content " : " Say hello in one short sentence .
"}
16 ],
17 }
18
19 response = requests . post ( url , headers = headers , json = body , timeout =60)
20 response . raise_for_status () # raises if status >= 400
21 data = response . json ()
22 print ( data [ " choices " ][0][ " message " ][ " content " ])

Note
json=body tells requests to serialize the dict and set Content-Type. Prefer this over
manually calling [Link].

4.2 Async requests with httpx


Async I/O helps when you call many APIs concurrently (e.g., batch embeddings).
1 import os
2 import httpx
3 import asyncio
4 from dotenv import load_dotenv
5

6 load_dotenv ()
7
8 async def chat ( prompt : str ) -> str :
9 url = " https :// api . openai . com / v1 / chat / completions "
10 headers = {
11 " Authorization " : f " Bearer { os . getenv ( ’ OPENAI_API_KEY ’) } " ,

Developed by Cyber Wolf 6 Basic → Intermediate


Python & API Basics for AI Apps Cyber Wolf

12 " Content - Type " : " application / json " ,


13 }
14 body = {
15 " model " : " gpt -4 o - mini " ,
16 " messages " : [{ " role " : " user " , " content " : prompt }] ,
17 }
18 async with httpx . AsyncClient ( timeout =60.0) as client :
19 r = await client . post ( url , headers = headers , json = body )
20 r . raise_for_status ()
21 data = r . json ()
22 return data [ " choices " ][0][ " message " ][ " content " ]
23
24 async def main () -> None :
25 answers = await asyncio . gather (
26 chat ( " Define REST in 10 words . " ) ,
27 chat ( " Define JSON in 10 words . " ) ,
28 )
29 for a in answers :
30 print ( a )
31
32 asyncio . run ( main () )

4.3 Official SDKs vs raw HTTP

Approach When to use


Raw requests/httpx Learning, custom endpoints, debugging
Official SDK (openai, etc.) Production apps: retries, streaming helpers

Same call with the OpenAI SDK:


1 from openai import OpenAI
2
3 client = OpenAI () # reads OPENAI_API_KEY from env
4
5 completion = client . chat . completions . create (
6 model = " gpt -4 o - mini " ,
7 messages =[{ " role " : " user " , " content " : " Explain HTTP status 429. "
}] ,
8 )
9 print ( completion . choices [0]. message . content )

5 Core Patterns in AI APIs


5.1 Chat messages and roles
Most chat models expect a list of messages with roles:
• system — behavior / policy instructions
• user — end-user input
• assistant — prior model replies (for multi-turn chat)
• tool — results returned from tools / functions
1 messages = [

Developed by Cyber Wolf 7 Basic → Intermediate


Python & API Basics for AI Apps Cyber Wolf

2 { " role " : " system " , " content " : " Answer briefly . Prefer bullet
points . " } ,
3 { " role " : " user " , " content " : " What is temperature in LLMs ? " } ,
4 ]

5.2 Embeddings
Embeddings turn text into vectors for search, clustering, and RAG.
1 from openai import OpenAI
2
3 client = OpenAI ()
4 resp = client . embeddings . create (
5 model = " text - embedding -3 - small " ,
6 input =[ " API basics " , " Python requests library " ] ,
7 )
8 vector = resp . data [0]. embedding
9 print ( len ( vector ) , vector [:5]) # dimension + first few floats

5.3 Streaming responses


Streaming returns tokens as they are generated—better UX for chat UIs.
1 from openai import OpenAI
2
3 client = OpenAI ()
4 stream = client . chat . completions . create (
5 model = " gpt -4 o - mini " ,
6 messages =[{ " role " : " user " , " content " : " Count from 1 to 5 slowly . "
}] ,
7 stream = True ,
8 )
9
10 for chunk in stream :
11 delta = chunk . choices [0]. delta . content
12 if delta :
13 print ( delta , end = " " , flush = True )
14 print ()

5.4 Retries and backoff


Transient failures (429, 503, network blips) should be retried with exponential backoff.
1 import time
2 import random
3 import requests
4
5 def po st_wit h_retr ies ( url , headers , json_body , max_attempts =5) :
6 delay = 1.0
7 for attempt in range (1 , max_attempts + 1) :
8 try :
9 r = requests . post ( url , headers = headers , json = json_body ,
timeout =60)
10 if r . status_code in (429 , 500 , 502 , 503 , 504) :
11 raise requests . HTTPError ( f " retryable : { r . status_code }
" , response = r )
12 r . raise_for_status ()

Developed by Cyber Wolf 8 Basic → Intermediate


Python & API Basics for AI Apps Cyber Wolf

13 return r . json ()
14 except ( requests . Timeout , requests . ConnectionError , requests .
HTTPError ) as exc :
15 if attempt == max_attempts :
16 raise
17 sleep_for = delay + random . uniform (0 , 0.5)
18 print ( f " Attempt { attempt } failed ({ exc }) ; sleeping {
sleep_for :.1 f } s " )
19 time . sleep ( sleep_for )
20 delay *= 2

Tip
Many official SDKs already include retries. Still understand the pattern so you can tune
it for your own microservices.

6 Validating Data with Pydantic


Loose dictionaries break at runtime. Pydantic models validate shapes at the boundary of your
app.
1 from pydantic import BaseModel , Field , ValidationError
2
3 class ChatRequest ( BaseModel ) :
4 prompt : str = Field ( min_length =1 , max_length =4000)
5 temperature : float = Field ( default =0.2 , ge =0.0 , le =2.0)
6 model : str = " gpt -4 o - mini "
7
8 try :
9 req = ChatRequest ( prompt = " Hello " , temperature =0.5)
10 print ( req . model_dump () ) # clean dict for API body
11 except ValidationError as e :
12 print ( e )

This pattern pairs naturally with FastAPI (next section): request bodies are validated automati-
cally.

7 Building Your Own API with FastAPI


AI features often live behind your own backend so the browser never sees raw provider keys.

7.1 Minimal chat endpoint


1 # app . py
2 import os
3 from fastapi import FastAPI , HTTPException
4 from pydantic import BaseModel , Field
5 from openai import OpenAI
6 from dotenv import load_dotenv
7
8 load_dotenv ()
9 app = FastAPI ( title = " AI Demo API " )
10 client = OpenAI ()
11

12 class ChatIn ( BaseModel ) :

Developed by Cyber Wolf 9 Basic → Intermediate


Python & API Basics for AI Apps Cyber Wolf

13 prompt : str = Field ( min_length =1 , max_length =4000)


14
15 class ChatOut ( BaseModel ) :
16 answer : str
17
18 @app . get ( " / health " )
19 def health () :
20 return { " status " : " ok " }
21

22 @app . post ( " / chat " , response_model = ChatOut )


23 def chat ( body : ChatIn ) :
24 if not os . getenv ( " OPENAI_API_KEY " ) :
25 raise HTTPException ( status_code =500 , detail = " API key not
configured " )
26 try :
27 completion = client . chat . completions . create (
28 model = " gpt -4 o - mini " ,
29 messages =[{ " role " : " user " , " content " : body . prompt }] ,
30 )
31 text = completion . choices [0]. message . content or " "
32 return ChatOut ( answer = text )
33 except Exception as exc :
34 raise HTTPException ( status_code =502 , detail = str ( exc ) ) from
exc

Run it:
1 uvicorn app : app -- reload -- port 8000
2 # Docs : http : // 12 7. 0. 0. 1: 80 00 / docs

Call it from another script:


1 import requests
2
3 r = requests . post (
4 " http : // 12 7. 0. 0. 1: 80 00 / chat " ,
5 json ={ " prompt " : " What is FastAPI in one sentence ? " } ,
6 timeout =60 ,
7 )
8 print ( r . json () )

Note
Interactive OpenAPI docs at /docs are excellent for learning request and response shapes
without writing a client first.

8 Intermediate: Tools / Function Calling


Models can request that your code run a tool (weather, database lookup, calculator). Your app
then feeds the result back.
1 import json
2 from openai import OpenAI
3
4 client = OpenAI ()
5
6 tools = [

Developed by Cyber Wolf 10 Basic → Intermediate


Python & API Basics for AI Apps Cyber Wolf

7 {
8 " type " : " function " ,
9 " function " : {
10 " name " : " get_weather " ,
11 " description " : " Get current weather for a city " ,
12 " parameters " : {
13 " type " : " object " ,
14 " properties " : {
15 " city " : { " type " : " string " } ,
16 },
17 " required " : [ " city " ] ,
18 },
19 },
20 }
21 ]
22
23 def get_weather ( city : str ) -> dict :
24 # Replace with a real weather API call
25 return { " city " : city , " temp_c " : 28 , " condition " : " sunny " }
26
27 messages = [{ " role " : " user " , " content " : " Weather in Chennai ? " }]
28
29 first = client . chat . completions . create (
30 model = " gpt -4 o - mini " ,
31 messages = messages ,
32 tools = tools ,
33 )
34
35 msg = first . choices [0]. message
36 messages . append ( msg )
37
38 if msg . tool_calls :
39 for call in msg . tool_calls :
40 args = json . loads ( call . function . arguments )
41 result = get_weather (** args )
42 messages . append (
43 {
44 " role " : " tool " ,
45 " tool_call_id " : call . id ,
46 " content " : json . dumps ( result ) ,
47 }
48 )
49
50 final = client . chat . completions . create (
51 model = " gpt -4 o - mini " ,
52 messages = messages ,
53 tools = tools ,
54 )
55 print ( final . choices [0]. message . content )
56 else :
57 print ( msg . content )

Tip

Tools are just APIs (or local functions) exposed to the model with a JSON schema. The
same HTTP skills from earlier apply inside each tool implementation.

Developed by Cyber Wolf 11 Basic → Intermediate


Python & API Basics for AI Apps Cyber Wolf

9 Security and Production Checklist


1. Never put API keys in frontend JavaScript or public repos.
2. Store secrets in environment variables or a secret manager.
3. Validate all inbound requests (Pydantic / schema).
4. Set timeouts on every HTTP call.
5. Handle 429 and 5xx with backoff.
6. Log request IDs and latency; avoid logging raw prompts if they contain PII.
7. Cap max tokens and input length to control cost.
8. Use HTTPS in production; pin provider base URLs you trust.

Caution
If a key leaks, rotate it immediately in the provider dashboard and update your deployment
secrets.

10 Mini Project: Prompt → API → Answer


Put the pieces together in one small script.
1 " " " mini_ai_client . py
2 Flow : load env -> build payload -> POST -> parse JSON -> print answer
3 """
4 import os
5 import sys
6 import requests
7 from dotenv import load_dotenv
8
9 load_dotenv ()
10
11 API_URL = " https :// api . openai . com / v1 / chat / completions "
12 API_KEY = os . getenv ( " OPENAI_API_KEY " )
13
14 def ask ( prompt : str ) -> str :
15 if not API_KEY :
16 raise RuntimeError ( " Set OPENAI_API_KEY in . env " )
17 headers = {
18 " Authorization " : f " Bearer { API_KEY } " ,
19 " Content - Type " : " application / json " ,
20 }
21 body = {
22 " model " : " gpt -4 o - mini " ,
23 " messages " : [
24 { " role " : " system " , " content " : " Be concise . " } ,
25 { " role " : " user " , " content " : prompt } ,
26 ],
27 " temperature " : 0.2 ,
28 }
29 r = requests . post ( API_URL , headers = headers , json = body , timeout
=60)
30 r . raise_for_status ()
31 return r . json () [ " choices " ][0][ " message " ][ " content " ]
32

Developed by Cyber Wolf 12 Basic → Intermediate


Python & API Basics for AI Apps Cyber Wolf

33 if __name__ == " __main__ " :


34 question = " " . join ( sys . argv [1:]) or " What is an API ? "
35 print ( ask ( question ) )

1 python mini_ai_client . py " Explain REST vs SDK in two bullets "

11 Practice Exercises
1. Write a function that loads OPENAI API KEY and raises a clear error if missing.
2. Call a public HTTP API (e.g. a joke or weather API) with requests, print status code and
JSON keys.
3. Convert a Python dict to JSON and back; assert equality of nested values.
4. Add exponential backoff around a flaky endpoint (simulate with random failures).
5. Build a FastAPI POST /summarize endpoint that accepts {text: str} and returns {summary:
str}.
6. Extend the tool-calling example with a second tool, e.g. get time(timezone).
7. Stream a chat reply to the terminal character-by-character.

12 Quick Reference

Topic Remember
Virtual env Isolate deps; use .env for keys
JSON dict/list ↔ API bodies
HTTP Method + URL + headers + body
Auth Authorization: Bearer <key>
Success Check status; then .json()
SDK Prefer for production AI providers
FastAPI Your app becomes an API for clients
Tools Model requests JSON; you execute & return

You now have the Python and API foundations to build AI features confidently.

Developed by Cyber Wolf

Developed by Cyber Wolf 13 Basic → Intermediate

You might also like