In this lecture, you will learn advanced API concepts and participate in hands-on exercises to build real services. The course combines theory and practice to help you understand how APIs are utilized in actual projects. If you are unfamiliar with basic API concepts, please review the material on fundamental API concepts before proceeding.
Advanced API Concepts – Core Concepts for Service Development
1. Advanced API Concepts – Core Concepts for Service Development
1-1. Types of APIs and Practical Application Methods
APIs come in various types based on their purpose and functionality.
Understanding how each type is used and selecting the appropriate API for real-world projects is crucial.
1. REST API (Representational State Transfer)
- This is the most widely used API architecture.
- It uses HTTP requests for clients and servers to exchange data.
- Features: Lightweight, standardized, supports diverse clients
- Example:
GET /users/1→ Retrieve information for a specific userPOST /reviews→ Adding a new review
2. GraphQL API
- Clients can request only the data they need.
- Features: More flexible than REST and prevents unnecessary data calls.
- Example:
{
user(id: "1") {
name
email
reviews {
title
rating
}
}
}
3. WebSocket API
- Suitable for real-time data communication needs. (e.g., chat, real-time notifications)
- Features: Maintains a persistent connection for fast responses.
- Example: Implementing real-time review updates
4. Open API (Public API)
- An API provided for anyone to use.
- Example:
- TMDB API (Provides movie & drama data)
- OpenWeather API (Provides weather information)
- ChatGPT API (AI text generation API)
- 1-2. API Authentication and Security
- API security is critical.
- They must be protected to prevent unauthorized users from manipulating or accessing data.
- 1. API Authentication Methods
- API Key (Simple Method)
- When a user requests an API key, it must be included in the API request header.
- Example:
Authorization: Bearer YOUR_API_KEY
- OAuth 2.0 (SNS Login, Permission Management)
- Used for Google, Facebook login, etc.
- This method involves obtaining an Access Token for authentication.
- JWT (JSON Web Token) – Enhanced Security
- When the client logs in, the server issues a JWT.
- and subsequent requests are authenticated by including the JWT.
- 2. Methods for Enhancing API Security
- Use HTTPS (SSL/TLS Encryption)
- API Request Limiting (Rate Limiting)
- CORS Configuration (Cross-Origin Resource Sharing)
2. API Practice – Building a Real Service
Practical Project: "Building a Sad Drama Recommendation API"
2-1. Project Goals and Service Flow
Project Goal
- When a user leaves a review for a sad drama, the API saves the data
- The API recommends sad dramas through AI analysis
- Display recommendation results on the website using the API
Service Flow
- User leaves a review → API stores it in the database
- API analyzes user sentiment (using AI)
- API recommends dramas with similar emotional tones from the database
- API returns recommended dramas to the website
3. Practice 1: API Design and Data Modeling
3-1. API Design (Endpoint Definition)
| HTTP Method | Endpoint | Description |
|---|---|---|
POST | /reviews | Add User Review |
GET | /reviews/{drama} | Retrieve Reviews for a Specific Drama |
GET | /recommend/{user} | Recommend Sad Dramas Tailored to the User |
3-2. Data Model Design
DB Table Structure (Based on PostgreSQL)
| ID | User | Drama Title | Sentiment Score (0~1) | Review Content |
|---|---|---|---|---|
| 1 | content | My Mister | 0.9 | It was such a moving drama T_T |
| 2 | flow | Mr. Sunshine | 0.85 | You can't watch it without tears… |
4. Practice 2: Building an API with FastAPI
4-1. Installing FastAPI and Basic Configuration
bash example code
pip install fastapi uvicorn psycopg2
4-2. Writing Basic API Code
Python example code
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Review(BaseModel):
user: str
drama: str
rating: int
review: str
@app.post("/reviews")
def add_review(review: Review):
return {"message": f"{review.drama}에 대한 리뷰가 저장되었습니다!"}
4-3. Running and Testing
Bash example code
uvicorn main:app --reload
API Call Example (POST Request)
HTTP Example Code
POST /reviews
{
"user": "content",
"drama": "나의 아저씨",
"rating": 5,
"review": "정말 감동적이었어요!"
}
5. Practice 3: Adding AI Sentiment Analysis & Recommendation Features
5-1. Integrating the Sentiment Analysis API
Python example code
from transformers import pipeline
emotion_model = pipeline("text-classification", model="j-hartmann/emotion-english-distilroberta-base")
def analyze_emotion(text):
result = emotion_model(text)
return result[0]["score"] if result[0]["label"] == "sadness" else 0.0
5-2. Implementing the AI Recommendation System
Python example code
@app.get("/recommend/{user}")
def recommend_drama(user: str):
# 슬픈 감성 점수가 높은 드라마 추천
return {"recommended": ["나의 아저씨", "미스터 션샤인"]}
API Request & Response Example
HTTP Example Code
GET /recommend/content
{
"recommended": ["나의 아저씨", "미스터 션샤인"]
}
6. API Deployment and Website Integration – Practical Application
Now, we'll learn how to deploy the FastAPI-based API we built to a real server and call it from a React website. We'll test if the API
works properly after deployment and proceed through the process of optimizing its performance.
6-1. FastAPI Deployment (Using AWS, Vercel, Heroku)
We must deploy the API built with FastAPI to run on a web server so anyone can use it. Popular
deployment methods include AWS, Vercel, and Heroku.
Essential Concepts for FastAPI Deployment
- Server Execution Method: While FastAPI uses
uvicorn, but
requires a WSGI server likegunicornWSGI servers like - Choosing a cloud server: You must select a platform like AWS, Vercel, or Heroku.
- Domain Connection: Ensure the deployed API
http://localhost:8000to operate on the same domain.https://myapi.comto the same domain.
Method 1: Deploying with AWS EC2
AWS EC2 (Elastic Compute Cloud) provides virtual servers in the cloud, enabling you to deploy your API.
1. Create an EC2 instance
- Create an EC2 instance in the AWS console.
- Select Ubuntu 20.04 or Amazon Linux
- Minimum spec: t2.micro (free)
2. Deploy FastAPI to EC2
Connect to the EC2 instance via SSH Execute the following code
ssh -i your-key.pem ubuntu@your-ec2-ip
Install Python and packages
sudo apt update && sudo apt upgrade -y
sudo apt install python3-pip -y
pip3 install fastapi uvicorn
Run the API
uvicorn main:app --host 0.0.0.0 --port 8000
Configure the firewall
- You must open port 8000 in the AWS security group.
http://your-ec2-ip:8000/docsVerify the API is functioning.
3. Optimizing Deployment with Nginx & Gunicorn
3-1. Install and Run Gunicorn
pip install gunicorn
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
3-2. Nginx Configuration (Reverse Proxy)
sudo apt install nginx -y
sudo nano /etc/nginx/sites-available/api
nginx복사편집server {
listen 80;
server_name your-api.com;
location / {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
3-3. Start Services After Applying Nginx
sudo ln -s /etc/nginx/sites-available/api /etc/nginx/sites-enabled
sudo systemctl restart nginx
3-4. Connect Domain and Apply SSL Certificate
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d your-api.com
You can now use FastAPI at https://your-api.com!
Method 2: Deploying with Vercel
Vercel is a service that allows you to deploy FastAPI applications for free.
1. Create a Vercel account and install the CLI
npm install -g vercel
vercel login
2. Connect your FastAPI project to Vercel and deploy
vercel
Now https://your-api.vercel.appyou can use the API.
Method 3: Deploying to Heroku
Heroku is a cloud service that allows you to easily deploy APIs.
1. Install the Heroku CLI
curl https://cli-assets.heroku.com/install.sh | sh
heroku login
2. Deploy your FastAPI project to Heroku
heroku create your-api-name
git push heroku main
The API is now availablehttps://your-api.herokuapp.com at [URL].
6-2. Calling the API from a React Website to Display Results
Let's learn how to call the API deployed with FastAPI from a React website to fetch data.
1. Setting up the React project
npx create-react-app my-app
cd my-app
npm start
2. Calling the API in React (using useEffect + fetch)
javascript
import { useEffect, useState } from "react";
function App() {
const [data, setData] = useState([]);
useEffect(() => {
fetch("https://your-api.com/recommend/content")
.then(response => response.json())
.then(result => setData(result.recommended));
}, []);
return (
<div>
<h1>추천 드라마</h1>
<ul>
{data.map((drama, index) => (
<li key={index}>{drama}</li>
))}
</ul>
</div>
);
}
export default App;
3. Configuring CORS (Allowing React Requests in FastAPI)
FastAPI blocks CORS requests by default for security reasons.
To successfully call the API from React, you must add CORS configuration in FastAPI.
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 특정 도메인만 허용 가능
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
You can now successfully call the API from React.
6-3. Testing and Optimization
This process involves verifying the API is deployed correctly and optimizing its performance.
1. Utilizing API Testing Tools
- Postman: Manually send API requests to verify responses
- cURL: Test API calls from the terminal
curl -X GET "https://your-api.com/recommend/content
- Utilize FastAPI's built-in `
/docs`:https://your-api.com/docsVerify API documentation automatically
2. Optimizing API Response Speed
- Apply Redis caching: Store frequently requested data in Redis
- Database Indexing: Improve search speed by adding indexes in SQL
- Gunicorn + Nginx Combination: Setting up a high-performance web server
3. Add logging and monitoring
- Using
loggingto store API call logs - Integration with monitoring tools like AWS CloudWatch and Grafana
7. Final Project Cleanup
- Store user reviews in the database using the API
- Recommend sad dramas after sentiment analysis using AI
- Display recommendation results by calling the API on the website
8. Practical Project Ideas for Hands-on Learning
- AI-based News Summarization API
- Real-time chat API (using WebSocket)
- SNS Login API (using OAuth 2.0)
Key technical concepts overview (Nginx, Gunicorn, Vercel, Heroku, React, CORS, FastAPI)
| Terminology | Description | Primary Role | Usage Examples |
|---|---|---|---|
| Nginx | Web server and reverse proxy server | Serving static files, load balancing, enhancing security | Distributes website traffic, manages requests in front of API servers |
| Gunicorn | Python WSGI server | Runs applications like FastAPI, Django, Flask | When deploying FastAPI, gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app Use |
| Vercel | Cloud deployment platform | Deploy static sites and backend servers | Free deployment support for React, Next.js, FastAPI, and more |
| Heroku | Platform as a Service (PaaS) | Automatically deploys servers when you upload your code | git push heroku mainDeploy FastAPI |
| React | Frontend library | Build web apps based on UI components | useState, useEffectData management using |
| CORS | Security Policy (Cross-Origin Resource Sharing Prevention) | Allowing API requests from external domains | FastAPI allow_origins=["*"] Configuration required |
| FastAPI | Python-based web framework | Enables easy and rapid API development | @app.get("/") Enables API routing |
