본문 바로가기

카테고리 없음

네이버 단축URL api 사용 예제

네이버 단축URL 공식 문서 : https://developers.naver.com/docs/utils/shortenurl/

 

단축 URL API 적용 가이드

단축 URL API는 원본 URL을 `https://me2.do/example`과 같은 형태의 짧은 URL로 반환하는 RESTful API입니다.

developers.naver.com

 

 

 

영상보기

https://youtu.be/g-v2M_5dAyw?si=ggKBshgPhjjEIQqS 

 

 

 


 

네이버 단축 URL api 사용 방법

 

1. naver developer 페이지로 이동 ( https://developers.naver.com/main/ )

2. 상단 메뉴 : “Application” > “내 어플리케이션” 으로 이동…

 

 

3. 

팔복소프트 - 네이버 단축URL

 

“Application 등록” 버튼 클릭

 

4.

팔복소프트 - 네이버 단축URL

내용 입력 후 “등록하기” 버튼 클릭

 

5.

팔복소프트 - 네이버 단축URL

“Client Id”와 “Client Secret” 를 활용해서 API를 사용 합니다.

 

 

 


NestJS 로 간단하게 만들어보기

- 목표

   
단축 URL 생성
[POST] {{url}}/v1/short-url
body
{
    "orgUrl": "https://www.naver.com"
}
단축 URL 리스트
[GET] {{url}}/v1/short-url/all
 

 

1. 설치

npx @nestjs/cli new short-url

cd short-url

npm install --save axios

code .

 

2. 간단한 시연 용으로 dataBase 대신 JSON 파일 사용하겠습니다.

  • src/data/data.json” 파일 생성

 

 

3. controller, service, module 생성

 

npx nest g resource v1/short-url

# src/v1/short-rul/dto/create-short-url-form.dto.ts

export class CreateShortUrlFormDto {
    orgUrl: string;
}

# src/v1/short-rul/dto/short-url-data.dto.ts

export class ShortUrlDataDto {
    url: string;
    hash: string;
    orgUrl: string;
    urlQr?: string;
}

# src/v1/short-rul/short-url.controller.ts

import { Body, Controller, Get, Post } from '@nestjs/common';
import { ShortUrlService } from './short-url.service';
import { CreateShortUrlFormDto } from './dto/create-short-url-form.dto';
import { ShortUrlDataDto } from './dto/short-url-data.dto';

@Controller('v1/short-url')
export class ShortUrlController {
    constructor(private readonly shortUrlService: ShortUrlService) {}

    @Post()
    async createShortUrl(
        @Body() body: CreateShortUrlFormDto,
    ): Promise<ShortUrlDataDto> {
        const orgUrl = body?.orgUrl;
        return await this.shortUrlService.createShortUrl(orgUrl);
    }

    @Get('all')
    async findShortUrlAll(): Promise<ShortUrlDataDto[]> {
        return await this.shortUrlService.findShortUrlAll();
    }
}

# src/v1/short-rul/short-url.service.ts

import {
    HttpException,
    Injectable,
    InternalServerErrorException,
} from '@nestjs/common';
import { ShortUrlDataDto } from './dto/short-url-data.dto';
import axios from 'axios';
import { writeFile, readFile } from 'fs/promises';

@Injectable()
export class ShortUrlService {
    private readonly jsonDataPath = './src/data/data.json';

    // 데이터 리스트
    async findDataAll(): Promise<ShortUrlDataDto[]> {
        const data = await readFile(this.jsonDataPath, 'utf8');
        if (!data) {
            return [];
        }
        return JSON.parse(data);
    }

    // 데이터 추가
    async addData(newData: ShortUrlDataDto): Promise<void> {
        const data = await this.findDataAll();
        data.push(newData);
        await writeFile(this.jsonDataPath, JSON.stringify(data), 'utf8');
    }

    // 단축 url 생성
    async createShortUrl(orgUrl: string): Promise<ShortUrlDataDto> {
        try {
            const url = 'https://openapi.naver.com/v1/util/shorturl';
            const headers = {
                headers: {
                    'X-Naver-Client-Id': 'yjJ_FDpGOIyUigh91oPP',
                    'X-Naver-Client-Secret': 'jybWBTXsii',
                },
            };
            const shortUrlResult = await axios.get(
                url + `?url=${encodeURIComponent(orgUrl)}`,
                headers,
            );
            // console.log(shortUrlResult);
            const resultData = shortUrlResult?.data;

            if (resultData?.code === '200' && resultData?.message === 'ok') {
                const data = {
                    url: resultData?.result?.url,
                    urlQr: `${resultData?.result?.url}.qr`,
                    orgUrl: resultData?.result?.orgUrl,
                    hash: resultData?.result?.hash,
                } as ShortUrlDataDto;
                await this.addData(data);
                return data;
            } else {
                throw new InternalServerErrorException('short url 생성 실패');
            }
        } catch (error) {
            console.log(error);
            if (error instanceof HttpException) {
                throw error;
            }
            throw new InternalServerErrorException();
        }
    }

    // 단축 URL 리스트
    async findShortUrlAll(): Promise<ShortUrlDataDto[]> {
        try {
            return await this.findDataAll();
        } catch (error) {
            console.log(error);
            if (error instanceof HttpException) {
                throw error;
            }
            throw new InternalServerErrorException();
        }
    }
}

# src/v1/short-rul/short-url.module.ts

import { Module } from '@nestjs/common';
import { ShortUrlService } from './short-url.service';
import { ShortUrlController } from './short-url.controller';

@Module({
    controllers: [ShortUrlController],
    providers: [ShortUrlService],
})
export class ShortUrlModule {}

4. start

npm run start:debug

 

포스트맨으로 localhost:3000 테스트 해보기