Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Info

swagger는 여러 플랫폼을 API문서화 자동화를 지원하는 툴입니다.


준비과정

swagger를 사용하기위해 1번만 해주면 되는 준비과정입니다.

swagger설치

Code Block
languagepowershell
themeEmacs
Install-Package Swashbuckle.AspNetCore

...

Code Block
languagec#
themeEmacs
linenumberstrue
collapsetrue
namespace accountapi
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices( IServiceCollection services )
        {
     
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure( IApplicationBuilder app, IHostingEnvironment env )
        {
            app.UseStaticFiles();

            if ( env.IsDevelopment() )
            {
                using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
                {
                }
                app.UseDeveloperExceptionPage();               
            }

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), 
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");                
            });

            app.UseSession();
            app.UseMvc();
        }
    }
}


Project.csproj 수정

Code Block
languagec#
themeEmacs
  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <DockerTargetOS>Linux</DockerTargetOS>
    <!-- 추가하기 --!>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <NoWarn>$(NoWarn);1591</NoWarn>
  </PropertyGroup>

프로젝트에서 우클릭하여 .csproj를 수정합니다.


launchSetting.json 수정

Code Block
languagec#
themeEmacs
.........
"accountapi": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger/",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "http://localhost:5000"
},

개발환경에서 swagger 문서를 시작페이지로 시작하려면 위와같이 설정을 합니다. ( 옵션 )


지속적 문서화와 테스트

API에 문서화기능 적용하기

Code Block
languagec#
themeEmacs
/// <summary>
/// 로그인후 자신의 계정처리에 필요한 accessToken을 할당받습니다.
/// </summary>
/// <param name="user"></param>   
[HttpPost("login")]
public ActionResult<LoginRes> PostUser([FromBody] LoginReq user)
{    
    if (!ModelState.IsValid)
    {                
        return BadRequest(ModelState);
    }
    LoginRes result = new LoginRes();
    return Ok(result);    
}

위와같이 주석을 달게되면, API 에대한 추가적인 설명을 기입할수가 있습니다.

주석을 달지 않더라도 기본적으로 API문서화가 자동화가 됩니다. 

Image Added


API Test하기

Image Added

swagger의 핵심은, 단순하게 문서화가 아니라 API를 Test를 할수 있는 UI까지 제공해줍니다.


추가참고자료



AccountControler

POST/api/account/login
로그인후 자신의 계정처리에 필요한 accessToken을 할당받습니다.

Parameters

NameDescription
user
(body)


Responses

Curl

Request URL

http://localhost:5000/api/account/login

Server response

CodeDetails
200
Response body
Download
{ "nick": "Mynick1", "accessToken": "NnJGUFY5akkwRTJ2Q2F3THVzdlZNUT09" }
Response headers
 content-type: application/json; charset=utf-8  date: Fri, 28 Sep 2018 17:04:28 GMT  server: Kestrel  transfer-encoding: chunked 


Responses

CodeDescription
200
Success
{ "nick": "string", "accessToken": "string" }