updated example

This commit is contained in:
Tony Tam 2013-03-21 21:44:19 -07:00 committed by George Sibble
parent e8e8c18c8f
commit f167959a38
14 changed files with 290 additions and 324 deletions

View File

@ -37,6 +37,8 @@ object ScalatraServerGenerator extends BasicScalaGenerator {
override def apiPackage = Some("apis")
// supporting classes
override def supportingFiles = List(
("README.mustache", outputFolder, "README.md"),
@ -57,6 +59,10 @@ object ScalatraServerGenerator extends BasicScalaGenerator {
val paramList = k._2.asInstanceOf[List[_]]
paramList.foreach(param => {
val map = param.asInstanceOf[scala.collection.mutable.HashMap[String, AnyRef]]
if(map.contains("dataType")){
val dataType = map("dataType")
map += "dataType" -> dataType.toString.replaceAll("Array\\[","List[")
}
if(map.contains("required")) {
if(map("required") == "false") map += "notRequired" -> "true"
}

View File

@ -3,13 +3,13 @@ import com.github.siasia.PluginKeys._
assemblySettings
organization := "org.eatbacon"
organization := "com.wordnik"
seq(webSettings :_*)
mainClass in assembly := Some("JettyMain")
name := "sfth"
name := "scalatra-sample"
version := "0.1.0-SNAPSHOT"

View File

@ -11,7 +11,7 @@ class ScalatraBootstrap extends LifeCycle {
context mount (new PetApi, "/pet/*")
context mount (new StoreApi, "/store/*")
context mount (new UserApi, "/user/*")
context mount (new ResourcesApp, "/*")
context mount (new ResourcesApp, "/api-docs/*")
} catch {
case e: Throwable => e.printStackTrace()
}

View File

@ -18,7 +18,7 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet
protected val applicationDescription: String = "PetApi"
override protected val applicationName: Option[String] = Some("pet")
/*
def swaggerToModel(cls: Class[_]) = {
val docObj = ApiPropertiesReader.read(cls)
val name = docObj.getName
@ -27,96 +27,79 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet
Model(name, name, fields.toMap)
}
*/
before() {
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
get("/:petId",
summary("Find pet by ID"),
nickname("getPetById"),
responseClass("Pet"),
endpoint("{petId}"),
notes("Returns a pet based on ID"),
parameters(
Parameter(name = "petId",
description = "ID of pet that needs to be fetched",
dataType = DataType.String,
defaultValue = None,
paramType = ParamType.Path)
)) {
// do something
val getPetByIdOperation = (apiOperation[Pet]("getPetById")
summary "Find pet by ID"
parameters(
pathParam[String]("petId").description(""))
)
get("/:petId",operation(getPetByIdOperation)) {
val petId = params.getOrElse("petId", halt(400))
println(petId)
}
post("/",
summary("Add a new pet to the store"),
nickname("addPet"),
responseClass("void"),
endpoint(""),
notes(""),
parameters(
Parameter(name = "body",
description = "Pet object that needs to be added to the store",
dataType = DataType("Pet"),
paramType = ParamType.Body)
)) {
// do something
val addPetOperation = (apiOperation[Unit]("addPet")
summary "Add a new pet to the store"
parameters(
bodyParam[Pet]("body").description(""))
)
post("/",operation(addPetOperation)) {
val body = parsedBody.extract[Pet]
println(body)
}
put("/",
summary("Update an existing pet"),
nickname("updatePet"),
responseClass("void"),
endpoint(""),
notes(""),
parameters(
Parameter(name = "body",
description = "Pet object that needs to be updated in the store",
dataType = DataType("Pet"),
paramType = ParamType.Body)
)) {
// do something
val updatePetOperation = (apiOperation[Unit]("updatePet")
summary "Update an existing pet"
parameters(
bodyParam[Pet]("body").description(""))
)
put("/",operation(updatePetOperation)) {
val body = parsedBody.extract[Pet]
println(body)
}
get("/findByStatus",
summary("Finds Pets by status"),
nickname("findPetsByStatus"),
responseClass("List[Pet]"),
endpoint("findByStatus"),
notes("Multiple status values can be provided with comma seperated strings"),
parameters(
Parameter(name = "status",
description = "Status values that need to be considered for filter",
paramType = ParamType.Query,
required = true,
allowMultiple = true,
defaultValue = Some("available"),
dataType = DataType("String"))
)) {
// do something
val findPetsByStatusOperation = (apiOperation[List[Pet]]("findPetsByStatus")
summary "Finds Pets by status"
parameters(
queryParam[String]("status").description("").defaultValue("available"))
)
get("/findByStatus",operation(findPetsByStatusOperation)) {
val status = params.getAs[String]("status")
println(status)
}
get("/findByTags",
summary("Finds Pets by tags"),
nickname("findPetsByTags"),
responseClass("List[Pet]"),
endpoint("findByTags"),
notes("Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing."),
parameters(
Parameter(name = "tags",
description = "Tags to filter by",
paramType = ParamType.Query,
required = true,
allowMultiple = true,
defaultValue = None,
dataType = DataType("String"))
)) {
// do something
val findPetsByTagsOperation = (apiOperation[List[Pet]]("findPetsByTags")
summary "Finds Pets by tags"
parameters(
queryParam[String]("tags").description(""))
)
get("/findByTags",operation(findPetsByTagsOperation)) {
val tags = params.getAs[String]("tags")
println(tags)
}
}

View File

@ -18,7 +18,7 @@ class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet
protected val applicationDescription: String = "StoreApi"
override protected val applicationName: Option[String] = Some("store")
/*
def swaggerToModel(cls: Class[_]) = {
val docObj = ApiPropertiesReader.read(cls)
val name = docObj.getName
@ -27,59 +27,51 @@ class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet
Model(name, name, fields.toMap)
}
*/
before() {
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
get("/order/:orderId",
summary("Find purchase order by ID"),
nickname("getOrderById"),
responseClass("Order"),
endpoint("order/{orderId}"),
notes("For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors"),
parameters(
Parameter(name = "orderId",
description = "ID of pet that needs to be fetched",
dataType = DataType.String,
defaultValue = None,
paramType = ParamType.Path)
)) {
// do something
val getOrderByIdOperation = (apiOperation[Order]("getOrderById")
summary "Find purchase order by ID"
parameters(
pathParam[String]("orderId").description(""))
)
get("/order/:orderId",operation(getOrderByIdOperation)) {
val orderId = params.getOrElse("orderId", halt(400))
println(orderId)
}
delete("/order/:orderId",
summary("Delete purchase order by ID"),
nickname("deleteOrder"),
responseClass("void"),
endpoint("order/{orderId}"),
notes("For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors"),
parameters(
Parameter(name = "orderId",
description = "ID of the order that needs to be deleted",
dataType = DataType.String,
defaultValue = None,
paramType = ParamType.Path)
)) {
// do something
val deleteOrderOperation = (apiOperation[Unit]("deleteOrder")
summary "Delete purchase order by ID"
parameters(
pathParam[String]("orderId").description(""))
)
delete("/order/:orderId",operation(deleteOrderOperation)) {
val orderId = params.getOrElse("orderId", halt(400))
println(orderId)
}
post("/order",
summary("Place an order for a pet"),
nickname("placeOrder"),
responseClass("void"),
endpoint("order"),
notes(""),
parameters(
Parameter(name = "body",
description = "order placed for purchasing the pet",
dataType = DataType("Order"),
paramType = ParamType.Body)
)) {
// do something
val placeOrderOperation = (apiOperation[Unit]("placeOrder")
summary "Place an order for a pet"
parameters(
bodyParam[Order]("body").description(""))
)
post("/order",operation(placeOrderOperation)) {
val body = parsedBody.extract[Order]
println(body)
}
}

View File

@ -18,7 +18,7 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet
protected val applicationDescription: String = "UserApi"
override protected val applicationName: Option[String] = Some("user")
/*
def swaggerToModel(cls: Class[_]) = {
val docObj = ApiPropertiesReader.read(cls)
val name = docObj.getName
@ -27,150 +27,123 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet
Model(name, name, fields.toMap)
}
*/
before() {
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
}
post("/createWithArray",
summary("Creates list of users with given input array"),
nickname("createUsersWithArrayInput"),
responseClass("void"),
endpoint("createWithArray"),
notes(""),
parameters(
Parameter(name = "body",
description = "List of user object",
dataType = DataType("Array[User]"),
paramType = ParamType.Body)
)) {
// do something
val createUsersWithArrayInputOperation = (apiOperation[Unit]("createUsersWithArrayInput")
summary "Creates list of users with given input array"
parameters(
bodyParam[List[User]]("body").description(""))
)
post("/createWithArray",operation(createUsersWithArrayInputOperation)) {
val body = parsedBody.extract[List[User]]
println(body)
}
post("/",
summary("Create user"),
nickname("createUser"),
responseClass("void"),
endpoint(""),
notes("This can only be done by the logged in user."),
parameters(
Parameter(name = "body",
description = "Created user object",
dataType = DataType("User"),
paramType = ParamType.Body)
)) {
// do something
val createUserOperation = (apiOperation[Unit]("createUser")
summary "Create user"
parameters(
bodyParam[User]("body").description(""))
)
post("/",operation(createUserOperation)) {
val body = parsedBody.extract[User]
println(body)
}
post("/createWithList",
summary("Creates list of users with given list input"),
nickname("createUsersWithListInput"),
responseClass("void"),
endpoint("createWithList"),
notes(""),
parameters(
Parameter(name = "body",
description = "List of user object",
dataType = DataType("List[User]"),
paramType = ParamType.Body)
)) {
// do something
val createUsersWithListInputOperation = (apiOperation[Unit]("createUsersWithListInput")
summary "Creates list of users with given list input"
parameters(
bodyParam[List[User]]("body").description(""))
)
post("/createWithList",operation(createUsersWithListInputOperation)) {
val body = parsedBody.extract[List[User]]
println(body)
}
put("/:username",
summary("Updated user"),
nickname("updateUser"),
responseClass("void"),
endpoint("{username}"),
notes("This can only be done by the logged in user."),
parameters(
Parameter(name = "username",
description = "name that need to be deleted",
dataType = DataType.String,
defaultValue = None,
paramType = ParamType.Path)
,Parameter(name = "body",
description = "Updated user object",
dataType = DataType("User"),
paramType = ParamType.Body)
)) {
// do something
val updateUserOperation = (apiOperation[Unit]("updateUser")
summary "Updated user"
parameters(
pathParam[String]("username").description(""),bodyParam[User]("body").description(""))
)
put("/:username",operation(updateUserOperation)) {
val username = params.getOrElse("username", halt(400))
println(username)
val body = parsedBody.extract[User]
println(body)
}
delete("/:username",
summary("Delete user"),
nickname("deleteUser"),
responseClass("void"),
endpoint("{username}"),
notes("This can only be done by the logged in user."),
parameters(
Parameter(name = "username",
description = "The name that needs to be deleted",
dataType = DataType.String,
defaultValue = None,
paramType = ParamType.Path)
)) {
// do something
val deleteUserOperation = (apiOperation[Unit]("deleteUser")
summary "Delete user"
parameters(
pathParam[String]("username").description(""))
)
delete("/:username",operation(deleteUserOperation)) {
val username = params.getOrElse("username", halt(400))
println(username)
}
get("/:username",
summary("Get user by user name"),
nickname("getUserByName"),
responseClass("User"),
endpoint("{username}"),
notes(""),
parameters(
Parameter(name = "username",
description = "The name that needs to be fetched. Use user1 for testing.",
dataType = DataType.String,
defaultValue = None,
paramType = ParamType.Path)
)) {
// do something
val getUserByNameOperation = (apiOperation[User]("getUserByName")
summary "Get user by user name"
parameters(
pathParam[String]("username").description(""))
)
get("/:username",operation(getUserByNameOperation)) {
val username = params.getOrElse("username", halt(400))
println(username)
}
get("/login",
summary("Logs user into the system"),
nickname("loginUser"),
responseClass("String"),
endpoint("login"),
notes(""),
parameters(
Parameter(name = "username",
description = "The user name for login",
paramType = ParamType.Query,
required = true,
allowMultiple = false,
defaultValue = None,
dataType = DataType("String"))
,Parameter(name = "password",
description = "The password for login in clear text",
paramType = ParamType.Query,
required = true,
allowMultiple = false,
defaultValue = None,
dataType = DataType("String"))
)) {
// do something
val loginUserOperation = (apiOperation[String]("loginUser")
summary "Logs user into the system"
parameters(
queryParam[String]("username").description(""),queryParam[String]("password").description(""))
)
get("/login",operation(loginUserOperation)) {
val username = params.getAs[String]("username")
println(username)
val password = params.getAs[String]("password")
println(password)
}
get("/logout",
summary("Logs out current logged in user session"),
nickname("logoutUser"),
responseClass("void"),
endpoint("logout"),
notes(""),
parameters(
)) {
// do something
}
val logoutUserOperation = (apiOperation[Unit]("logoutUser")
summary "Logs out current logged in user session"
parameters(
)
)
get("/logout",operation(logoutUserOperation)) {
}
}

View File

@ -1,8 +1,9 @@
package com.wordnik.client.model
import scala.reflect.BeanProperty
case class Category (
id: Long,
name: String)
id: Option[Long],
name: Option[String]
)

View File

@ -1,13 +1,16 @@
package com.wordnik.client.model
import java.util.Date
import scala.reflect.BeanProperty
case class Order (
id: Long,
petId: Long,
/* Order Status */
status: String,
quantity: Int,
shipDate: Date)
id: Option[Long],
petId: Option[Long],
status: Option[String],// Order Status
quantity: Option[Int],
shipDate: Option[Date]
)

View File

@ -2,14 +2,18 @@ package com.wordnik.client.model
import com.wordnik.client.model.Category
import com.wordnik.client.model.Tag
import scala.reflect.BeanProperty
case class Pet (
tags: List[Tag],
id: Long,
category: Category,
/* pet status in the store */
status: String,
name: String,
photoUrls: List[String])
tags: Option[List[Tag]],
id: Option[Long],
category: Option[Category],
status: Option[String],// pet status in the store
name: Option[String],
photoUrls: Option[List[String]]
)

View File

@ -1,8 +1,9 @@
package com.wordnik.client.model
import scala.reflect.BeanProperty
case class Tag (
id: Long,
name: String)
id: Option[Long],
name: Option[String]
)

View File

@ -1,15 +1,21 @@
package com.wordnik.client.model
import scala.reflect.BeanProperty
case class User (
id: Long,
lastName: String,
phone: String,
username: String,
email: String,
/* User Status */
userStatus: Int,
firstName: String,
password: String)
id: Option[Long],
lastName: Option[String],
phone: Option[String],
username: Option[String],
email: Option[String],
userStatus: Option[Int],// User Status
firstName: Option[String],
password: Option[String]
)

View File

@ -12,7 +12,7 @@ class ScalatraBootstrap extends LifeCycle {
context mount (new {{className}}, "/{{name}}/*")
{{/apis}}
context mount (new ResourcesApp, "/*")
context mount (new ResourcesApp, "/api-docs/*")
} catch {
case e: Throwable => e.printStackTrace()
}

View File

@ -19,7 +19,7 @@ class {{className}} (implicit val swagger: Swagger) extends ScalatraServlet
protected val applicationDescription: String = "{{className}}"
override protected val applicationName: Option[String] = Some("{{baseName}}")
/*
def swaggerToModel(cls: Class[_]) = {
val docObj = ApiPropertiesReader.read(cls)
val name = docObj.getName
@ -28,7 +28,7 @@ class {{className}} (implicit val swagger: Swagger) extends ScalatraServlet
Model(name, name, fields.toMap)
}
*/
before() {
contentType = formats("json")
response.headers += ("Access-Control-Allow-Origin" -> "*")
@ -36,49 +36,49 @@ class {{className}} (implicit val swagger: Swagger) extends ScalatraServlet
{{#operations}}
{{#operation}}
{{newline}}
{{httpMethod}}("{{path}}",
summary("{{{summary}}}"),
nickname("{{nickname}}"),
responseClass("{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}}"),
endpoint("{{basePart}}"),
notes("{{{notes}}}"),
parameters(
{{#allParams}}
{{#queryParameter}}
Parameter(name = "{{paramName}}",
description = "{{{description}}}",
paramType = ParamType.Query,
required = {{required}},
allowMultiple = {{allowMultiple}},
{{#allowableValues}}allowableValues = {{{allowableValues}}},{{newline}}{{/allowableValues}}
defaultValue = {{#defaultValue}}Some({{{defaultValue}}}){{/defaultValue}}{{^defaultValue}}None{{/defaultValue}},
dataType = DataType("{{dataType}}"))
{{/queryParameter}}
{{#pathParameter}}
Parameter(name = "{{paramName}}",
description = "{{{description}}}",
dataType = DataType.String,
{{#allowableValues}}allowableValues = {{{allowableValues}}},{{newline}}{{/allowableValues}}
defaultValue = {{#defaultValue}}Some({{{defaultValue}}}){{/defaultValue}}{{^defaultValue}}None{{/defaultValue}},
paramType = ParamType.Path)
{{/pathParameter}}
{{#headerParameter}}
Parameter(name = "{{paramName}}",
description = "{{{description}}}",
dataType = DataType("{{dataType}}"),
paramType = ParamType.Header)
{{/headerParameter}}
{{#bodyParameter}}
Parameter(name = "{{paramName}}",
description = "{{{description}}}",
dataType = DataType("{{dataType}}"),
paramType = ParamType.Body)
{{/bodyParameter}}{{#hasMore}},{{/hasMore}}
{{/allParams}}
)) {
// do something
val {{nickname}}Operation = (apiOperation[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]("{{nickname}}")
summary "{{{summary}}}"
parameters(
{{#allParams}}
{{#queryParameter}}
queryParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}
{{/queryParameter}}
{{#pathParameter}}
pathParam[{{dataType}}]("{{paramName}}").description(""){{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}
{{/pathParameter}}
{{#headerParameter}}
headerParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}
{{/headerParameter}}
{{#bodyParameter}}
bodyParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}
{{/bodyParameter}}
{{#hasMore}},{{/hasMore}}
{{/allParams}})
)
{{httpMethod}}("{{path}}",operation({{nickname}}Operation)) {
{{#allParams}}
{{#pathParameter}}
val {{paramName}} = params.getOrElse("{{paramName}}", halt(400))
{{/pathParameter}}
{{#queryParameter}}
val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}")
{{/queryParameter}}
{{#headerParameter}}
val {{paramName}} = request.getHeader("{{paramName}}")
{{/headerParameter}}
{{#bodyParameter}}
val {{paramName}} = parsedBody.extract[{{dataType}}]
{{/bodyParameter}}
println({{paramName}})
{{/allParams}}
}
{{/operation}}
{{/operations}}
}

View File

@ -4,15 +4,12 @@ package {{package}}
{{/imports}}
{{#models}}
import scala.reflect.BeanProperty
{{#model}}
case class {{classname}} (
{{#vars}}
{{#description}}/* {{description}} */
{{/description}}
{{name}}: {{datatype}}{{#hasMore}},{{newline}} {{/hasMore}}
{{name}}: {{#isNotRequired}}Option[{{/isNotRequired}}{{datatype}}{{#isNotRequired}}]{{/isNotRequired}} {{#hasMore}},{{/hasMore}}{{#description}} // {{description}}{{/description}}{{newline}}
{{/vars}}
)
{{/model}}