Go Programming

Go Programming

1629893521

How to Build a RESTful API Server with Go and Gin

This tutorial introduces the basics of writing a RESTful web service API with Go and the Gin Web Framework (Gin).

You’ll get the most out of this tutorial if you have a basic familiarity with Go and its tooling. If this is your first exposure to Go, please see Tutorial: Get started with Go for a quick introduction.

Gin simplifies many coding tasks associated with building web applications, including web services. In this tutorial, you’ll use Gin to route requests, retrieve request details, and marshal JSON for responses.

In this tutorial, you will build a RESTful API server with two endpoints. Your example project will be a repository of data about vintage jazz records.

The tutorial includes the following sections:

  1. Design API endpoints.
  2. Create a folder for your code.
  3. Create the data.
  4. Write a handler to return all items.
  5. Write a handler to add a new item.
  6. Write a handler to return a specific item.

To try this as an interactive tutorial you complete in Google Cloud Shell, click the button below.

Open in Cloud Shell

Prerequisites

  • An installation of Go 1.16 or later. For installation instructions, see Installing Go.
  • A tool to edit your code. Any text editor you have will work fine.
  • A command terminal. Go works well using any terminal on Linux and Mac, and on PowerShell or cmd in Windows.
  • The curl tool. On Linux and Mac, this should already be installed. On Windows, it’s included on Windows 10 Insider build 17063 and later. For earlier Windows versions, you might need to install it. For more, see Tar and Curl Come to Windows.

Design API endpoints

You’ll build an API that provides access to a store selling vintage recordings on vinyl. So you’ll need to provide endpoints through which a client can get and add albums for users.

When developing an API, you typically begin by designing the endpoints. Your API’s users will have more success if the endpoints are easy to understand.

Here are the endpoints you’ll create in this tutorial.

/albums

  • GET – Get a list of all albums, returned as JSON.
  • POST – Add a new album from request data sent as JSON.

/albums/:id

  • GET – Get an album by its ID, returning the album data as JSON.

Next, you’ll create a folder for your code.

Create a folder for your code

To begin, create a project for the code you’ll write.

Open a command prompt and change to your home directory.

On Linux or Mac:

$ cd

On Windows:

C:\> cd %HOMEPATH%

Using the command prompt, create a directory for your code called web-service-gin.

$ mkdir web-service-gin
$ cd web-service-gin

Create a module in which you can manage dependencies.

Run the go mod init command, giving it the path of the module your code will be in.

$ go mod init example.com/web-service-gin
go: creating new go.mod: module example.com/web-service-gin

This command creates a go.mod file in which dependencies you add will be listed for tracking. For more, be sure to see Managing dependencies.

Next, you’ll design data structures for handling data.

Create the data

To keep things simple for the tutorial, you’ll store data in memory. A more typical API would interact with a database.

Note that storing data in memory means that the set of albums will be lost each time you stop the server, then recreated when you start it.

Write the code

Using your text editor, create a file called main.go in the web-service directory. You’ll write your Go code in this file.

Into main.go, at the top of the file, paste the following package declaration.

package main

A standalone program (as opposed to a library) is always in package main.

Beneath the package declaration, paste the following declaration of an album struct. You’ll use this to store album data in memory.

Struct tags such as json:"artist" specify what a field’s name should be when the struct’s contents are serialized into JSON. Without them, the JSON would use the struct’s capitalized field names – a style not as common in JSON.

// album represents data about a record album.
type album struct {
    ID     string  `json:"id"`
    Title  string  `json:"title"`
    Artist string  `json:"artist"`
    Price  float64 `json:"price"`
}

Beneath the struct declaration you just added, paste the following slice of album structs containing data you’ll use to start.

// albums slice to seed record album data.
var albums = []album{
    {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
    {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
    {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

Next, you’ll write code to implement your first endpoint.

Write a handler to return all items

When the client makes a request at GET /albums, you want to return all the albums as JSON.

To do this, you’ll write the following:

  • Logic to prepare a response
  • Code to map the request path to your logic

Note that this is the reverse of how they’ll be executed at runtime, but you’re adding dependencies first, then the code that depends on them.

Write the code

Beneath the struct code you added in the preceding section, paste the following code to get the album list.

This getAlbums function creates JSON from the slice of album structs, writing the JSON into the response.

// getAlbums responds with the list of all albums as JSON.
func getAlbums(c *gin.Context) {
    c.IndentedJSON(http.StatusOK, albums)
}

In this code, you:

Write a getAlbums function that takes a gin.Context parameter. Note that you could have given this function any name – neither Gin nor Go require a particular function name format.

gin.Context is the most important part of Gin. It carries request details, validates and serializes JSON, and more. (Despite the similar name, this is different from Go’s built-in context package.)

Call Context.IndentedJSON to serialize the struct into JSON and add it to the response.

The function’s first argument is the HTTP status code you want to send to the client. Here, you’re passing the StatusOK constant from the net/http package to indicate 200 OK.

Note that you can replace Context.IndentedJSON with a call to Context.JSON to send more compact JSON. In practice, the indented form is much easier to work with when debugging and the size difference is usually small.

Near the top of main.go, just beneath the albums slice declaration, paste the code below to assign the handler function to an endpoint path.

func main() {
    router := gin.Default()
    router.GET("/albums", getAlbums)

    router.Run("localhost:8080")
}

This sets up an association in which getAlbums handles requests to the /albums endpoint path.

In this code, you:

Initialize a Gin router using Default.

Use the GET function to associate the GET HTTP method and /albums path with a handler function.

Note that you’re passing the name of the getAlbums function. This is different from passing the result of the function, which you would do by passing getAlbums() (note the parenthesis).

Use the Run function to attach the router to an http.Server and start the server.

Near the top of main.go, just beneath the package declaration, import the packages you’ll need to support the code you’ve just written.

The first lines of code should look like this:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

Save main.go.

Run the code

Begin tracking the Gin module as a dependency.

At the command line, use go get to add the github.com/gin-gonic/gin module as a dependency for your module. Use a dot argument to mean “get dependencies for code in the current directory.”

$ go get .
go get: added github.com/gin-gonic/gin v1.7.2

Go resolved and downloaded this dependency to satisfy the import declaration you added in the previous step.

From the command line in the directory containing main.go, run the code. Use a dot argument to mean “run code in the current directory.”

$ go run .

Once the code is running, you have a running HTTP server to which you can send requests.

From a new command line window, use curl to make a request to your running web service.

$ curl http://localhost:8080/albums

The command should display the data you seeded the service with.

[
        {
                "id": "1",
                "title": "Blue Train",
                "artist": "John Coltrane",
                "price": 56.99
        },
        {
                "id": "2",
                "title": "Jeru",
                "artist": "Gerry Mulligan",
                "price": 17.99
        },
        {
                "id": "3",
                "title": "Sarah Vaughan and Clifford Brown",
                "artist": "Sarah Vaughan",
                "price": 39.99
        }
]

You’ve started an API! In the next section, you’ll create another endpoint with code to handle a POST request to add an item.

Write a handler to add a new item

When the client makes a POST request at /albums, you want to add the album described in the request body to the existing albums data.

To do this, you’ll write the following:

  • Logic to add the new album to the existing list.
  • A bit of code to route the POST request to your logic.

Write the code

Add code to add albums data to the list of albums.

Somewhere after the import statements, paste the following code. (The end of the file is a good place for this code, but Go doesn’t enforce the order in which you declare functions.)

// postAlbums adds an album from JSON received in the request body.
func postAlbums(c *gin.Context) {
    var newAlbum album

    // Call BindJSON to bind the received JSON to
    // newAlbum.
    if err := c.BindJSON(&newAlbum); err != nil {
        return
    }

    // Add the new album to the slice.
    albums = append(albums, newAlbum)
    c.IndentedJSON(http.StatusCreated, newAlbum)
}

In this code, you:

  • Use Context.BindJSON to bind the request body to newAlbum.
  • Append the album struct initialized from the JSON to the albums slice.
  • Add a 201 status code to the response, along with JSON representing the album you added.

Change your main function so that it includes the router.POST function, as in the following.

func main() {
    router := gin.Default()
    router.GET("/albums", getAlbums)
    router.POST("/albums", postAlbums)

    router.Run("localhost:8080")
}

In this code, you:

Associate the POST method at the /albums path with the postAlbums function.

With Gin, you can associate a handler with an HTTP method-and-path combination. In this way, you can separately route requests sent to a single path based on the method the client is using.

Run the code

If the server is still running from the last section, stop it.

From the command line in the directory containing main.go, run the code.

$ go run .

From a different command line window, use curl to make a request to your running web service.

$ curl http://localhost:8080/albums \
    --include \
    --header "Content-Type: application/json" \
    --request "POST" \
    --data '{"id": "4","title": "The Modern Sound of Betty Carter","artist": "Betty Carter","price": 49.99}'

The command should display headers and JSON for the added album.

HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Date: Wed, 02 Jun 2021 00:34:12 GMT
Content-Length: 116

{
    "id": "4",
    "title": "The Modern Sound of Betty Carter",
    "artist": "Betty Carter",
    "price": 49.99
}

As in the previous section, use curl to retrieve the full list of albums, which you can use to confirm that the new album was added.

$ curl http://localhost:8080/albums \
    --header "Content-Type: application/json" \
    --request "GET"

The command should display the album list.

[
        {
                "id": "1",
                "title": "Blue Train",
                "artist": "John Coltrane",
                "price": 56.99
        },
        {
                "id": "2",
                "title": "Jeru",
                "artist": "Gerry Mulligan",
                "price": 17.99
        },
        {
                "id": "3",
                "title": "Sarah Vaughan and Clifford Brown",
                "artist": "Sarah Vaughan",
                "price": 39.99
        },
        {
                "id": "4",
                "title": "The Modern Sound of Betty Carter",
                "artist": "Betty Carter",
                "price": 49.99
        }
]

In the next section, you’ll add code to handle a GET for a specific item.

Write a handler to return a specific item

When the client makes a request to GET /albums/[id], you want to return the album whose ID matches the id path parameter.

To do this, you will:

  • Add logic to retrieve the requested album.
  • Map the path to the logic.

Write the code

Beneath the postAlbums function you added in the preceding section, paste the following code to retrieve a specific album.

This getAlbumByID function will extract the ID in the request path, then locate an album that matches.

// getAlbumByID locates the album whose ID value matches the id
// parameter sent by the client, then returns that album as a response.
func getAlbumByID(c *gin.Context) {
    id := c.Param("id")

    // Loop over the list of albums, looking for
    // an album whose ID value matches the parameter.
    for _, a := range albums {
        if a.ID == id {
            c.IndentedJSON(http.StatusOK, a)
            return
        }
    }
    c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}

In this code, you:

Use Context.Param to retrieve the id path parameter from the URL. When you map this handler to a path, you’ll include a placeholder for the parameter in the path.

Loop over the album structs in the slice, looking for one whose ID field value matches the id parameter value. If it’s found, you serialize that album struct to JSON and return it as a response with a 200 OK HTTP code.

As mentioned above, a real-world service would likely use a database query to perform this lookup.

Return an HTTP 404 error with http.StatusNotFound if the album isn’t found.

Finally, change your main so that it includes a new call to router.GET, where the path is now /albums/:id, as shown in the following example.

func main() {
    router := gin.Default()
    router.GET("/albums", getAlbums)
    router.GET("/albums/:id", getAlbumByID)
    router.POST("/albums", postAlbums)

    router.Run("localhost:8080")
}

In this code, you:

  • Associate the /albums/:id path with the getAlbumByID function. In Gin, the colon preceding an item in the path signifies that the item is a path parameter.

Run the code

If the server is still running from the last section, stop it.

From the command line in the directory containing main.go, run the code to start the server.

$ go run .

From a different command line window, use curl to make a request to your running web service.

$ curl http://localhost:8080/albums/2

The command should display JSON for the album whose ID you used. If the album wasn’t found, you’ll get JSON with an error message.

{
        "id": "2",
        "title": "Jeru",
        "artist": "Gerry Mulligan",
        "price": 17.99
}

Conclusion

Congratulations! You’ve just used Go and Gin to write a simple RESTful web service.

Suggested next topics:

Completed code

This section contains the code for the application you build with this tutorial.

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

// album represents data about a record album.
type album struct {
    ID     string  `json:"id"`
    Title  string  `json:"title"`
    Artist string  `json:"artist"`
    Price  float64 `json:"price"`
}

// albums slice to seed record album data.
var albums = []album{
    {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
    {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
    {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

func main() {
    router := gin.Default()
    router.GET("/albums", getAlbums)
    router.GET("/albums/:id", getAlbumByID)
    router.POST("/albums", postAlbums)

    router.Run("localhost:8080")
}

// getAlbums responds with the list of all albums as JSON.
func getAlbums(c *gin.Context) {
    c.IndentedJSON(http.StatusOK, albums)
}

// postAlbums adds an album from JSON received in the request body.
func postAlbums(c *gin.Context) {
    var newAlbum album

    // Call BindJSON to bind the received JSON to
    // newAlbum.
    if err := c.BindJSON(&newAlbum); err != nil {
        return
    }

    // Add the new album to the slice.
    albums = append(albums, newAlbum)
    c.IndentedJSON(http.StatusCreated, newAlbum)
}

// getAlbumByID locates the album whose ID value matches the id
// parameter sent by the client, then returns that album as a response.
func getAlbumByID(c *gin.Context) {
    id := c.Param("id")

    // Loop through the list of albums, looking for
    // an album whose ID value matches the parameter.
    for _, a := range albums {
        if a.ID == id {
            c.IndentedJSON(http.StatusOK, a)
            return
        }
    }
    c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}
{
        "id": "2",
        "title": "Jeru",
        "artist": "Gerry Mulligan",
        "price": 17.99
}

$ curl http://localhost:8080/albums/2

$ go run .

func main() {
    router := gin.Default()
    router.GET("/albums", getAlbums)
    router.GET("/albums/:id", getAlbumByID)
    router.POST("/albums", postAlbums)

    router.Run("localhost:8080")
}

// getAlbumByID locates the album whose ID value matches the id
// parameter sent by the client, then returns that album as a response.
func getAlbumByID(c *gin.Context) {
    id := c.Param("id")

    // Loop over the list of albums, looking for
    // an album whose ID value matches the parameter.
    for _, a := range albums {
        if a.ID == id {
            c.IndentedJSON(http.StatusOK, a)
            return
        }
    }
    c.IndentedJSON(http.StatusNotFound, gin.H{"message": "album not found"})
}

[
        {
                "id": "1",
                "title": "Blue Train",
                "artist": "John Coltrane",
                "price": 56.99
        },
        {
                "id": "2",
                "title": "Jeru",
                "artist": "Gerry Mulligan",
                "price": 17.99
        },
        {
                "id": "3",
                "title": "Sarah Vaughan and Clifford Brown",
                "artist": "Sarah Vaughan",
                "price": 39.99
        },
        {
                "id": "4",
                "title": "The Modern Sound of Betty Carter",
                "artist": "Betty Carter",
                "price": 49.99
        }
]

$ curl http://localhost:8080/albums \
    --header "Content-Type: application/json" \
    --request "GET"

HTTP/1.1 201 Created
Content-Type: application/json; charset=utf-8
Date: Wed, 02 Jun 2021 00:34:12 GMT
Content-Length: 116

{
    "id": "4",
    "title": "The Modern Sound of Betty Carter",
    "artist": "Betty Carter",
    "price": 49.99
}

$ curl http://localhost:8080/albums \
    --include \
    --header "Content-Type: application/json" \
    --request "POST" \
    --data '{"id": "4","title": "The Modern Sound of Betty Carter","artist": "Betty Carter","price": 49.99}'

$ go run .

func main() {
    router := gin.Default()
    router.GET("/albums", getAlbums)
    router.POST("/albums", postAlbums)

    router.Run("localhost:8080")
}

// postAlbums adds an album from JSON received in the request body.
func postAlbums(c *gin.Context) {
    var newAlbum album

    // Call BindJSON to bind the received JSON to
    // newAlbum.
    if err := c.BindJSON(&newAlbum); err != nil {
        return
    }

    // Add the new album to the slice.
    albums = append(albums, newAlbum)
    c.IndentedJSON(http.StatusCreated, newAlbum)
}

[
        {
                "id": "1",
                "title": "Blue Train",
                "artist": "John Coltrane",
                "price": 56.99
        },
        {
                "id": "2",
                "title": "Jeru",
                "artist": "Gerry Mulligan",
                "price": 17.99
        },
        {
                "id": "3",
                "title": "Sarah Vaughan and Clifford Brown",
                "artist": "Sarah Vaughan",
                "price": 39.99
        }
]

$ curl http://localhost:8080/albums

$ go run .

$ go get .
go get: added github.com/gin-gonic/gin v1.7.2

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()
    router.GET("/albums", getAlbums)

    router.Run("localhost:8080")
}

// getAlbums responds with the list of all albums as JSON.
func getAlbums(c *gin.Context) {
    c.IndentedJSON(http.StatusOK, albums)
}

// albums slice to seed record album data.
var albums = []album{
    {ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
    {ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
    {ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

// album represents data about a record album.
type album struct {
    ID     string  `json:"id"`
    Title  string  `json:"title"`
    Artist string  `json:"artist"`
    Price  float64 `json:"price"`
}

package main

$ go mod init example.com/web-service-gin
go: creating new go.mod: module example.com/web-service-gin

$ mkdir web-service-gin
$ cd web-service-gin

C:\> cd %HOMEPATH%

$ cd

The Original Article can be found on https://golang.org

#go #golang #programming 

 

What is GEEK

Buddha Community

How to Build a RESTful API Server with Go and Gin
Wilford  Pagac

Wilford Pagac

1594289280

What is REST API? An Overview | Liquid Web

What is REST?

The REST acronym is defined as a “REpresentational State Transfer” and is designed to take advantage of existing HTTP protocols when used for Web APIs. It is very flexible in that it is not tied to resources or methods and has the ability to handle different calls and data formats. Because REST API is not constrained to an XML format like SOAP, it can return multiple other formats depending on what is needed. If a service adheres to this style, it is considered a “RESTful” application. REST allows components to access and manage functions within another application.

REST was initially defined in a dissertation by Roy Fielding’s twenty years ago. He proposed these standards as an alternative to SOAP (The Simple Object Access Protocol is a simple standard for accessing objects and exchanging structured messages within a distributed computing environment). REST (or RESTful) defines the general rules used to regulate the interactions between web apps utilizing the HTTP protocol for CRUD (create, retrieve, update, delete) operations.

What is an API?

An API (or Application Programming Interface) provides a method of interaction between two systems.

What is a RESTful API?

A RESTful API (or application program interface) uses HTTP requests to GET, PUT, POST, and DELETE data following the REST standards. This allows two pieces of software to communicate with each other. In essence, REST API is a set of remote calls using standard methods to return data in a specific format.

The systems that interact in this manner can be very different. Each app may use a unique programming language, operating system, database, etc. So, how do we create a system that can easily communicate and understand other apps?? This is where the Rest API is used as an interaction system.

When using a RESTful API, we should determine in advance what resources we want to expose to the outside world. Typically, the RESTful API service is implemented, keeping the following ideas in mind:

  • Format: There should be no restrictions on the data exchange format
  • Implementation: REST is based entirely on HTTP
  • Service Definition: Because REST is very flexible, API can be modified to ensure the application understands the request/response format.
  • The RESTful API focuses on resources and how efficiently you perform operations with it using HTTP.

The features of the REST API design style state:

  • Each entity must have a unique identifier.
  • Standard methods should be used to read and modify data.
  • It should provide support for different types of resources.
  • The interactions should be stateless.

For REST to fit this model, we must adhere to the following rules:

  • Client-Server Architecture: The interface is separate from the server-side data repository. This affords flexibility and the development of components independently of each other.
  • Detachment: The client connections are not stored on the server between requests.
  • Cacheability: It must be explicitly stated whether the client can store responses.
  • Multi-level: The API should work whether it interacts directly with a server or through an additional layer, like a load balancer.

#tutorials #api #application #application programming interface #crud #http #json #programming #protocols #representational state transfer #rest #rest api #rest api graphql #rest api json #rest api xml #restful #soap #xml #yaml

An API-First Approach For Designing Restful APIs | Hacker Noon

I’ve been working with Restful APIs for some time now and one thing that I love to do is to talk about APIs.

So, today I will show you how to build an API using the API-First approach and Design First with OpenAPI Specification.

First thing first, if you don’t know what’s an API-First approach means, it would be nice you stop reading this and check the blog post that I wrote to the Farfetchs blog where I explain everything that you need to know to start an API using API-First.

Preparing the ground

Before you get your hands dirty, let’s prepare the ground and understand the use case that will be developed.

Tools

If you desire to reproduce the examples that will be shown here, you will need some of those items below.

  • NodeJS
  • OpenAPI Specification
  • Text Editor (I’ll use VSCode)
  • Command Line

Use Case

To keep easy to understand, let’s use the Todo List App, it is a very common concept beyond the software development community.

#api #rest-api #openai #api-first-development #api-design #apis #restful-apis #restful-api

Chaz  Homenick

Chaz Homenick

1602725748

Why You Should Consider Low-Code Approach to Building a REST API

APIs have been around for decades – they allow different systems to talk to each other in a seamless, fast fashion – yet it’s been during the past decade that this technology has become a significant force.

So then why all the interest in APIs? We all know the usual stories – Uber, Airbnb, Apple Pay… the list goes on, and the reasons are plentiful. Today the question is, how? Perhaps you are looking to differentiate your business or want a first-mover advantage.  How can you execute quickly and at low cost/risk to try new market offerings?

An API provides several benefits to an organisation, but without a dedicated team of trained developers, it might seem like an implausible option. Developers are expensive, and it can take months to develop an API from the ground up. If you don’t fancy outsourcing or have the capability in house to build internal APIs, a low-code platform might just be the answer.

Before You Begin: Plan long-term, start small.

For a small one-page application, this might only be a day or two of talking with stakeholders and designing business logic. The purpose of this first step is to ensure that the API will cover all use cases and provides stakeholders with what they need. Refactoring an entire coding design due to missing business logic is not only frustrating for the development team but adds high cost and time to the API project.

During the planning and design stage, remember that running an API requires more infrastructure than just resources to execute endpoint logic. You need a database to store the data, an email system to send messages, storage for files, and security to handle authorisation and authentication. These services can be farmed out to cloud providers to expedite the API build process (e.g. AWS provides all these infrastructure components, but Microsoft Azure is an optional cloud provider with SendGrid as the email application.)

**Planning considerations: **An API “speaks” in JSON or XML, so the output provided to client applications should be decided. Should you choose to later create endpoints for public developer consumption, you could offer both for ease-of-use and fostering more adoption. Ensuring the API follows OpenAPI standards will encourage more adoption and attract more developers.

#api #rest-api #api-development #restful-api #low-code-platform #low-code #build-a-rest-api #low-code-approach

Adonis  Kerluke

Adonis Kerluke

1596509565

RESTful API Design Driven Approach

In this tutorial I will show you the fundamentals of designing a RESTful API specification by applying REST principles and best practices, then you’ll be ready to try my online tutorial: How to design a REST API with API Designer?

If you already know what is meant by API in the context of RESTful web services, you can skip to the next section. If not, read on.

Level-Set on API

The abbreviation API stands for Application Programming Interface this in itself, does not help us understand what it is, however in the context of web services, it can refer to one of two things:

  1. The RESTful API specification is written using a modeling language such as Open API specification or RAML (RESTful API Modeling Language) that defines a contract for how software components can interact with a service.
  2. The implementation of a web service or microservice whose contract is designed by REST principles that describe how other services must interact with it.

In this post, I will use the first understanding of this term. Even though both are correct, the most technically relevant for this post is the first: an API is a contract for how software applications talk to each other.

Level-Set on REST

The acronym REST stands for REpresentational State Transfer. It is an architectural style used to represent the transmission of data from one application component to another. In the context of web services, we are talking about the representation of resources (i.e. data) transferred over HTTP by calling a URI that represents the data and via an HTTP method that represents the action to perform against the given data.

What Is RESTful API design?

RESTful API design is the activity of describing the behavior of a web service in terms of its data structures and the actions you allow other application components to perform on its data by the principles of REST. Those principles are covered later in this blog.

Why Design a RESTful API?

Imagine that you are an Architect (the kind the design building) and you set out to build an office block without a blueprint. You turn up on the first day with a truck full of bricks and some cement. What are the chances that you’ll be successful and build a structure that conforms to code and more importantly, doesn’t fall? It’s about zero. Without a blueprint the chance of failure is high.

The same approach applies to web service development. You need a blueprint, or more appropriately, an API specification. This is necessary to evaluate the API design and solicit feedback before even starting to build the implementation.

In addition to providing a specification for the web service’s development, an API contract serves to document its expected behavior, data types, and security requirements.

You should now be satisfied that API design is necessary for a RESTful web service, and should start to wonder how is the best approach to actually designing an API specification.

API Design Tooling

The tooling chosen by an API designer has substantial influence over the designer’s productivity. Highly productive tools such as the Anypoint API Designer from MuleSoft is perfect for designing APIs with OAS (swagger) or RAML.

#integration #api #rest #rest api #restful #api design #raml #rest api design