post-photo

Backend developers! Here’s how you should work with frontend developers!

Here is to establishing the perfect collaboration between backend developers and frontend developers!

Are you a backend developer?

If you’re a backend developer, I’m pretty sure you have experienced difficulties with cooperation during the development of a full stack software.

You always need to team up with many people and as the process progresses, the guys from the other side (I don’t mean the dark one, but the client) are eager to give your APIs a try. These clients may realize that, for whatever reason, you haven’t finished these APIs yet. However, the team needs to move on, so we need a tool that helps us out here.

And this is how we get acquainted with the world’s most popular framework for APIs: Swagger.

No, it’s not another hipster tech gadget. It is a simple yet powerful representation of your RESTful API – and it’s open source. With a Swagger-enabled API, backend developers get interactive documentation, client SDK generation, and discoverability.

text

So what can I do with it?

…you might ask.

As an API provider you have several approaches to begin with:

On the other hand, as an API consumer who wants to explore the interface, there is a dependency-free collection of HTML, JS and CSS assets that dynamically generate beautiful documentation for you (Swagger UI). You even have a chance to try them out – pretty cool, isn’t it?

Now, let’s peek into the specification!

The API specification

The previously mentioned Swagger Editor provides some examples, so you quickly get a sense of how it’s supposed to be done.

swagger: '2.0'
info:
  title: Uber API
  description: Move your app forward with the Uber API
  version: "1.0.0"
# the domain of the service
host: api.uber.com
# array of all schemes that your API supports
schemes:
  - https
# will be prefixed to all paths
basePath: /v1
produces:
  - application/json
paths:
  /products:
    get:
      summary: Product Types
      description: |
        The Products endpoint returns information about the *Uber* products
        offered at a given location. The response includes the display name
        and other details about each product, and lists the products in the
        proper display order.
      parameters:
        - name: latitude
          in: query
          description: Latitude component of location.
          required: true
          type: number
          format: double
        - name: longitude
          in: query
          description: Longitude component of location.
          required: true
          type: number
          format: double
      tags:
        - Products
      responses:
        200:
          description: An array of products
          schema:
            type: array
            items:
              $ref: '#/definitions/Product'
        default:
          description: Unexpected error
          schema:
            $ref: '#/definitions/Error'
definitions:
  Product:
    type: object
    properties:
      product_id:
        type: string
        description: Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles.
      description:
        type: string
        description: Description of product.
      display_name:
        type: string
        description: Display name of product.
      capacity:
        type: string
        description: Capacity of product. For example, 4 people.
      image:
        type: string
        description: Image URL representing the product.
  Error:
    type: object
    properties:
      code:
        type: integer
        format: int32
      message:
        type: string
      fields:
        type: string

As you can see the Swagger representation of the API is made of a single file. Most of the fields are pretty straightforward, so I’ll just pick a few to introduce in detail.

The root object requires three mandatory fields: the swagger version, the info and the paths object. The first must be ‘2.0’ as we are using the version 2.0 now. The info object provides metadata about the API, it’s mainly for clients. The paths describes the available paths and operations for the given API.

The paths contains the parameters object, where one can define a list of parameters that are applicable for the API. There are five parameter types (in field):

So, you can reference your models in the responses object. The definitions object holds data types produced and consumed by operations.

And finally, the corresponding request looks like this:

GET https://api.uber.com/v1/products?latitude=34.3&longitude=56.2 HTTP/1.1

Host: api.uber.com
Accept: application/json
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,fa;q=0.6,sv;q=0.4
Cache-Control: no-cache
Connection: keep-alive

If you’d like to dig in deeper, I suggest you visit Swagger’s GitHub wiki; you’ll find very detailed and neat documentation.

The annotations

If you already have a bunch of code at hand, you do not want to mess around with the editor to write your API again.

The easiest way to solve this is to add a set of annotations to your classes so you can generate the specification automatically. Swagger supports the most frequently used frameworks: Spring MVC, JAX-RS, Node.js or Play.

The annotations are grouped into three groups – the annotation to declare the resource, the set of annotations to declare an operation, and the set of annotations that declare API models.

Let me show you an example of how this works in the Play Framework.

@Api(value = "/user", description = "Operations about users")
public class SysUserController extends Controller {
 
@ApiOperation(
            value = "Resource to get a sysuser",
            notes = "note",
            httpMethod = "GET",
            response = SysUserBean.class)
@ApiResponses({ @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "User not found") })
public static Result getUser(
            @ApiParam(value = "user's id", required = true)
            @PathParam("id")
            Long id) {
   return ok("one user");
}

For all the details, please follow this link.

Backend developers’ conclusion

I think I speak not only for myself but for the majority of developers when I say the cooperation can be a pain in the *ss if the API isn’t specified well in the early stages of a project.

You can, of course, simultaneously write your documentation with the code. But why would you do the same job twice? Use Swagger for your – and your team’s – own sake!

Ps.: starting January 1st 2016 the Swagger Specification has been donated to to the Open API Initiative (OAI) and has been renamed to the OpenAPI Specification.

member photo

Likes to code in his spare time, and really likes to code after the caffeine rush.

Latest post by Csongor Zonda

Backend developers! Here’s how you should work with frontend developers!