한양과학기술고등학교

에듀테크 프로젝트 대시보드

Curl 문법 가이드

GET POST PUT / PATCH DELETE Bearer Auth File Upload

기본 문법 구조

curl의 기본 구조는 아래와 같습니다. 옵션 순서는 대부분 상관없으나, URL은 옵션 없이 단독으로 쓰거나 마지막에 위치시키는 것이 관례입니다.

curl  [옵션]  [URL]
# 예시
curl  -X POST  -H "Content-Type: application/json"  -d '{"name":"홍길동"}'  https://api.example.com/users
curl 이란?
  • Client URL의 약자. 터미널에서 HTTP 요청을 보내는 범용 도구입니다.
  • API 테스트, 파일 다운로드, 서버 헬스 체크 등 다양한 용도로 사용합니다.
  • FastAPI, Django, Spring 등 모든 서버와 통신 가능하며 macOS/Linux에 기본 내장되어 있습니다.

주요 옵션 목록

옵션이름설명 및 사용 예
-X메서드 지정HTTP 메서드를 명시. 기본값은 GET. -X POST, -X DELETE
-H헤더 추가요청 헤더를 추가. 여러 번 사용 가능. -H "Authorization: Bearer 토큰"
-d요청 바디POST/PUT 요청의 본문 데이터. -d '{"key":"value"}'
-F폼 데이터multipart/form-data 전송. 파일 업로드에 사용. -F "file=@photo.jpg"
-o파일 저장응답을 파일로 저장. -o result.json
-O파일명 유지URL의 파일명 그대로 저장. -O https://.../file.zip
-i헤더 포함 출력응답 헤더와 바디를 함께 출력
-I헤더만 출력HEAD 요청. 응답 헤더만 출력 (바디 없음)
-v상세 출력요청/응답 전체 과정을 출력. 디버깅에 유용
-s조용히 실행진행률 및 에러 메시지 숨김. 스크립트에서 활용
-uBasic Auth사용자명:비밀번호 형식. -u admin:1234
-L리다이렉트 추적301/302 리다이렉트를 자동으로 따라감
-kSSL 검증 생략자체 서명 인증서 등 SSL 오류 무시 (개발용)
--max-time타임아웃최대 대기 시간(초). --max-time 10
-c / -b쿠키-c cookie.txt 저장, -b cookie.txt 전송

GET 요청

curl의 기본 메서드는 GET입니다. -X GET은 생략해도 동일하게 동작합니다.

GET 기본 GET 요청
URL에 직접 접근. 가장 기본적인 형태입니다.
$curl https://jsonplaceholder.typicode.com/posts/1
Response
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere...",
  "body": "quia et suscipit..."
}
GET 쿼리 파라미터 전달
URL에 ?key=value 형식으로 검색 조건을 전달합니다.
$curl "https://jsonplaceholder.typicode.com/posts?userId=1&_limit=3"
  # URL에 &가 있으면 반드시 따옴표로 감싸세요
Response
[ { "userId": 1, "id": 1, ... },
  { "userId": 1, "id": 2, ... },
  { "userId": 1, "id": 3, ... } ]
HEAD 헤더만 확인
바디 없이 응답 헤더만 확인합니다. 서버 상태, Content-Type 점검에 유용합니다.
$curl -I https://jsonplaceholder.typicode.com/posts/1
Response Headers
HTTP/2 200
content-type: application/json; charset=utf-8
cache-control: max-age=43200

POST 요청

데이터를 서버로 전송할 때 사용합니다. -d로 JSON 바디를, -H로 Content-Type을 반드시 함께 지정합니다.

POST JSON 데이터 전송
가장 일반적인 REST API POST 요청 형태입니다.
$curl -X POST \
-H "Content-Type: application/json" \
-d '{"title":"curl 가이드","body":"내용","userId":1}' \
https://jsonplaceholder.typicode.com/posts
Response 201 Created
{ "id": 101, "title": "curl 가이드", "body": "내용", "userId": 1 }
POST Form 데이터 전송 (x-www-form-urlencoded)
HTML form의 일반 submit과 동일한 방식입니다.
$curl -X POST \
-d "username=hong&password=1234" \
http://localhost:8000/login
Response
{ "access_token": "eyJhbGci...", "token_type": "bearer" }

PUT / PATCH 요청

PUT은 리소스 전체를 교체하고, PATCH는 일부 필드만 수정합니다.

PUT 리소스 전체 교체
id=1 게시글의 모든 필드를 새 값으로 교체합니다.
$curl -X PUT \
-H "Content-Type: application/json" \
-d '{"id":1,"title":"수정된 제목","body":"수정된 내용","userId":1}' \
https://jsonplaceholder.typicode.com/posts/1
Response 200 OK
{ "id": 1, "title": "수정된 제목", ... }
PATCH 특정 필드만 수정
제목 하나만 변경합니다. 나머지 필드는 서버에서 기존 값을 유지합니다.
$curl -X PATCH \
-H "Content-Type: application/json" \
-d '{"title":"제목만 바꿈"}' \
https://jsonplaceholder.typicode.com/posts/1
Response 200 OK
{ "id": 1, "title": "제목만 바꿈", "body": "기존 내용 유지" }

DELETE 요청

리소스를 삭제합니다. 성공 시 보통 204 No Content 또는 빈 {}를 반환합니다.

DELETE 리소스 삭제
id=1 게시글을 삭제합니다.
$curl -X DELETE https://jsonplaceholder.typicode.com/posts/1
  # 응답 상태코드도 함께 보고 싶을 때
$curl -X DELETE -i https://jsonplaceholder.typicode.com/posts/1
Response 200 OK
{}

헤더 & 인증

Bearer Token 인증 (JWT)

FastAPI의 OAuth2PasswordBearer 등으로 보호된 엔드포인트에 접근할 때 사용합니다.

GET Bearer Token으로 인증된 요청
로그인 후 받은 JWT 토큰을 Authorization 헤더에 담아 전송합니다.
# 1단계: 로그인해서 토큰 받기
$curl -X POST -d "username=admin&password=1234" http://localhost:8000/token
# 2단계: 토큰으로 보호된 엔드포인트 접근
$curl -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
http://localhost:8000/users/me
Response
{ "id": 1, "username": "admin", "email": "admin@example.com" }
GET Basic Auth
-u 옵션으로 사용자명:비밀번호를 전달합니다. curl이 자동으로 Base64 인코딩합니다.
$curl -u admin:mypassword http://localhost:8000/admin/stats
  # 아래와 동일한 요청
$curl -H "Authorization: Basic YWRtaW46bXlwYXNzd29yZA==" http://localhost:8000/admin/stats
Response
{ "total_users": 142, "active_sessions": 37 }
POST 여러 헤더 동시 전송
-H를 여러 번 반복해서 헤더를 추가합니다.
$curl -X POST \
-H "Content-Type: application/json" \
-H "Authorization: Bearer 토큰값" \
-H "X-Request-ID: abc-123" \
-d '{"name":"테스트"}' \
http://localhost:8000/items
Response 201 Created
{ "id": 42, "name": "테스트", "created_at": "2026-06-08T09:00:00" }

파일 업로드

-F 옵션으로 multipart/form-data 방식의 파일 업로드를 할 수 있습니다. FastAPI의 UploadFile과 연동됩니다.

POST 단일 파일 업로드
파일 경로 앞에 @를 붙이면 해당 파일을 읽어서 전송합니다.
$curl -X POST \
-F "file=@/Users/hong/photo.jpg" \
http://localhost:8000/upload
Response
{ "filename": "photo.jpg", "size": 204800, "url": "/files/photo.jpg" }
POST 파일 + 추가 데이터 동시 전송
파일과 함께 텍스트 필드도 같이 전송할 수 있습니다.
$curl -X POST \
-F "file=@report.pdf" \
-F "title=2026년 보고서" \
-F "category=finance" \
http://localhost:8000/documents
Response
{ "id": 7, "title": "2026년 보고서", "category": "finance" }

디버깅 & 출력 제어

GET -v 상세 출력 (가장 많이 씀)
요청 헤더, 응답 헤더, 바디 전체를 모두 출력합니다. 오류 디버깅 시 필수입니다.
$curl -v http://localhost:8000/health
Verbose Output
* Trying 127.0.0.1:8000...
* Connected to localhost port 8000
> GET /health HTTP/1.1
> Host: localhost:8000
< HTTP/1.1 200 OK
< content-type: application/json
 
{ "status": "ok" }
GET 응답을 파일로 저장 & jq 파싱
응답 JSON을 파일로 저장하거나, jq로 예쁘게 출력합니다.
$curl -s -o result.json http://localhost:8000/students
  # jq로 예쁘게 출력 (jq 설치 필요)
$curl -s http://localhost:8000/students | jq .
jq 출력 결과
[
  { "id": 1, "name": "홍길동", "grade": 3 }
]

FastAPI 연동 실전 예제

실제 로컬 FastAPI 서버를 기준으로 한 curl 테스트 흐름입니다.

테스트 전 서버 확인
  • FastAPI 실행: uvicorn main:app --reload
  • Swagger UI 접속: http://localhost:8000/docs
  • curl로 헬스 체크: curl http://localhost:8000/
POST 로그인 → 토큰 획득 → API 호출 전체 흐름
FastAPI OAuth2 로그인부터 보호된 엔드포인트 호출까지 전체 흐름입니다.
# 1. 로그인 (토큰 획득)
$curl -X POST \
-d "username=teacher01&password=pass1234" \
http://localhost:8000/auth/token
# 2. 학생 목록 조회 (토큰 필요)
$curl \
-H "Authorization: Bearer <위에서받은토큰>" \
http://localhost:8000/students
# 3. 학생 등록 (POST + 토큰)
$curl -X POST \
-H "Authorization: Bearer <토큰>" \
-H "Content-Type: application/json" \
-d '{"name":"김철수","grade":2,"class_no":"3반"}' \
http://localhost:8000/students
Response 201 Created
{ "id": 58, "name": "김철수", "grade": 2, "class_no": "3반" }
✅ 자주 쓰는 패턴 요약
  • GET 조회: curl http://localhost:8000/items/1
  • POST JSON: curl -X POST -H "Content-Type: application/json" -d '{...}' URL
  • 인증 포함: curl -H "Authorization: Bearer 토큰" URL
  • 파일 업로드: curl -X POST -F "file=@파일경로" URL
  • 디버깅: curl -v URL 또는 응답만: curl -s URL | jq .
"curl은 API의 청진기다 — 서버가 살아있는지, 무슨 말을 하는지 직접 들어보자"