Edward Jackson

Edward Jackson

1558317112

Creating a Simple RESTful API in Go

In this tutorial demonstrates how you can create a simple RESTful JSON api using Go(Lang)

If you are writing any form of web application, then you are most likely interfacing with 1 or more REST APIs in order to populate the dynamic parts of your application and to perform tasks such as updating or deleting data within a database.

In this tutorial, you are going to be building a fully-fledged REST API that exposes GET, POST, DELETE and PUT endpoints that will subsequently allow you to perform the full range of CRUD operations.

In order to keep this simple and focus on the basic concepts, we won’t be interacting with any backend database technologies to store the articles that we’ll be playing with. However, we will be writing this REST API in such a way that it will be easy to update the functions we will be defining so that they make subsequent calls to a database to perform any necessary CRUD operations.

Source Code - The full source code for this article can be found here: TutorialEdge/create-rest-api-in-go-tutorial## Prerequisites

  • You will need Go version 1.11+ installed on your development machine.

Goals

By the end of this tutorial, you will know how to create your own REST-ful APIs in **Go **that can handle all aspects of. You will know how to create **REST **endpoints within your project that can handle POST, GET, PUT and DELETE HTTP requests.

Video Tutorial

REST Architectures

REST is everywhere these days, from websites to enterprise applications, the RESTful architecture style is a powerful way of providing communication between separate software components. Building REST APIs allow you to easily decouple both consumers and producers and are typically stateless by design.

Note - If you wish to learn more about the basics of REST APIs then check out What Are RESTful APIs?## JSON

For the purpose of this tutorial I’ll be using JavaScript Object Notation as a means of sending and receiving all information and thankfully Go comes with some excellent support for encoding and decoding these formats using the standard library package, encoding/json.

Note - For more information on the encoding/json package check out the official documentation: encoding/json## Marshalling

In order for us to easily We can easily convert data structures in GO into JSON by using something called marshalling which produces a byte slice containing a very long string with no extraneous white space.

Getting Started with A Basic API

To get started we will have to create a very simple server which can handle HTTP requests. To do this we’ll create a new file called main.go. Within this main.go file we’ll want to define 3 distinct functions. A homePage function that will handle all requests to our root URL, a handleRequests function that will match the URL path hit with a defined function and a main function which will kick off our API.

main.go

package main

import (
    "fmt"
    "log"
    "net/http"
)

func homePage(w http.ResponseWriter, r *http.Request){
    fmt.Fprintf(w, "Welcome to the HomePage!")
    fmt.Println("Endpoint Hit: homePage")
}

func handleRequests() {
    http.HandleFunc("/", homePage)
    log.Fatal(http.ListenAndServe(":10000", nil))
}

func main() {
    handleRequests()
}

If we run this on our machine now, we should see our very simple API start up on port 10000 if it’s not already been taken by another process. If we now navigate to <a href="http://localhost:10000/" target="_blank">http://localhost:10000/</a> in our local browser we should see Welcome to the HomePage! print out on our screen. This means we have successfully created the base from which we’ll build our REST API.

Note - If you want a more in-depth tutorial on how to create a go based web server then check out this tutorial here: Creating a Simple Web Server with Go(Lang)## Our Articles Structure

We’ll be creating a REST API that allows us to CREATE, READ, UPDATE and DELETE the articles on our website. When we talk about CRUD APIs we are referring to an API that can handle all of these tasks: Creating, Reading, Updating and Deleting.

Before we can get started, we’ll have to define our Article structure. Go has this concept of structs that are perfect for just this scenario. Let’s create an Article struct that features a Title, a Description (desc) and Content like so:

type Article struct {
    Title string `json:"Title"`
    Desc string `json:"desc"`
    Content string `json:"content"`
}

// let's declare a global Articles array
// that we can then populate in our main function
// to simulate a database
var Articles []Article

Our Struct contains the 3 properties we need to represent all of the articles on our site. In order for this to work, we’ll also have to import the "encoding/json" package into our list of imports.

Let’s now update our main function so that our Articles variable is populated with some dummy data that we can retrieve and modify later on.

func main() {
    articles := Articles{
        Article{Title: "Hello", Desc: "Article Description", Content: "Article Content"},
        Article{Title: "Hello 2", Desc: "Article Description", Content: "Article Content"},
    }
    handleRequests()
}

Perfect, let’s now move on to creating our /articles endpoint which will return all of the articles that we’ve just defined here.

Retrieving All Articles

In this part of the tutorial we are going to create a new REST endpoint which, when hit with a HTTP GET request, will return all of the articles for our site.

We’ll first start off by creating a new function called returnAllArticles, which will do the simple task of returning our newly populated Articles variable, encoded in JSON format:

main.go

func returnAllArticles(w http.ResponseWriter, r *http.Request){
    fmt.Println("Endpoint Hit: returnAllArticles")
    json.NewEncoder(w).Encode(Articles)
}

The call to json.NewEncoder(w).Encode(article) does the job of encoding our articles array into a JSON string and then writing as part of our response.

Before this will work, we’ll also need to add a new route to our handleRequests function that will map any calls to <a href="http://localhost:10000/articles" target="_blank">http://localhost:10000/articles</a> to our newly defined function.

func handleRequests() {
    http.HandleFunc("/", homePage)
    // add our articles route and map it to our 
    // returnAllArticles function like so
    http.HandleFunc("/articles", returnAllArticles)
    log.Fatal(http.ListenAndServe(":10000", nil))
}

Now that we’ve done this, run the code by typing go run main.go and then open up <a href="http://localhost:10000/articles" target="_blank">http://localhost:10000/articles</a> in your browser and you should see a JSON representation of your list of articles like so:

http://localhost:10000/articles response

[
  {
    Title: "Hello",
    desc: "Article Description",
    content: "Article Content"
  },
  {
    Title: "Hello 2",
    desc: "Article Description",
    content: "Article Content"
  }
];

We’ve successfully defined our first API endpoint.

In the next part of this series, you are going to update your REST API to use a gorilla/mux router instead of the traditional net/http router.

Swapping the routers will enable you to more easily perform tasks such as parsing any path or query parameters that may reside within an incoming HTTP request which we will need later on.

Getting Started with Routers

Now the standard library is adequate at providing everything you need to get your own simple REST API up and running but now that we’ve got the basic concepts down I feel it’s time to introduce third-party router packages. The most notable and highly used is the gorilla/mux router which, as it stands currently has 2,281 stars on Github.

Building our Router

We can update our existing main.go file and swap in a gorilla/mux based HTTP router in place of the standard library one which was present before.

Modify your handleRequests function so that it creates a new router.

main.go

package main

import (
    "fmt"
    "log"
    "net/http"
    "encoding/json"
    "github.com/gorilla/mux"
)

… // Existing code from above
func handleRequests() {
    // creates a new instance of a mux router
    myRouter := mux.NewRouter().StrictSlash(true)
    // replace http.HandleFunc with myRouter.HandleFunc
    myRouter.HandleFunc("/", homePage)
    myRouter.HandleFunc("/all", returnAllArticles)
    // finally, instead of passing in nil, we want
    // to pass in our newly created router as the second
    // argument
    log.Fatal(http.ListenAndServe(":10000", myRouter))
}

func main() {
    fmt.Println("Rest API v2.0 - Mux Routers")
    Articles = []Article{
        Article{Title: "Hello", Desc: "Article Description", Content: "Article Content"},
        Article{Title: "Hello 2", Desc: "Article Description", Content: "Article Content"},
    }
    handleRequests()
}

When you now run this, you will see no real change to the way our system works. It will still start up on the same port and return the same results depending on what endpoints you hit.

The only real difference is that we now have a gorilla/mux router which will allow us to easily do things such as retrieve path and query parameters later on in this tutorial.

$ go run main.go

Rest API v2.0 - Mux Routers

Path Variables

So far so good, we’ve created a very simple REST API that returns a homepage and all our Articles. But what happens if we want to just view one article?

Well, thanks to the gorilla mux router we can add variables to our paths and then pick and choose what articles we want to return based on these variables. Create a new route within your handleRequests() function just below our /articles route:

myRouter.HandleFunc("/article/{id}", returnSingleArticle)

Notice that we’ve added {id} to our path. This will represent our id variable that we’ll be able to use when we wish to return only the article that features that exact key. For now, our Article struct doesn’t feature an Id property. Let’s add that now:

type Article struct {
    Id      string `json:"Id"`
    Title   string `json:"Title"`
    Desc    string `json:"desc"`
    Content string `json:"content"`
}

We can then update our main function to populate our Id values in our Articles array:

func main() {
    Articles = []Article{
        Article{Id: "1", Title: "Hello", Desc: "Article Description", Content: "Article Content"},
        Article{Id: "2", Title: "Hello 2", Desc: "Article Description", Content: "Article Content"},
    }
    handleRequests()
}

Now that we’ve done that, in our returnSingleArticle function we can obtain this {id} value from our URL and we can return the article that matches this criteria. As we haven’t stored our data anywhere we’ll just be returning the Id that was passed to the browser.

func returnSingleArticle(w http.ResponseWriter, r *http.Request){
    vars := mux.Vars(r)
    key := vars["id"]

    fmt.Fprintf(w, "Key: " + key)
}

If we navigate to <a href="http://localhost:1000/article/1" target="_blank">http://localhost:1000/article/1</a>after we’ve now run this, you should see Key: 1 being printed out within the browser.

Let’s use this key value to return the specific article that matches that key.

func returnSingleArticle(w http.ResponseWriter, r *http.Request) {
    vars := mux.Vars(r)
    key := vars["id"]

    // Loop over all of our Articles
    // if the article.Id equals the key we pass in
    // return the article encoded as JSON
    for _, article := range Articles {
        if article.Id == key {
            json.NewEncoder(w).Encode(article)
        }
    }
}

Run that by calling go run main.go and then open up <a href="http://localhost:10000/article/1" target="_blank">http://localhost:10000/article/1</a> in your browser:

http://localhost:10000/article/1 response

{
Id: "1",
Title: "Hello",
desc: "Article Description",
content: "Article Content"
}

You will now see the article matching the key 1 returned as JSON.

Creating and Updating Articles

In this part of the tutorial, you are going to build the Create, Update and DELETE part of a CRUD REST API. We have already covered the R with the ability to read both single articles and all articles.

Creating new Articles

Once again, you will need to create a new function which will do the job of creating this new article.

Let’s start off by creating a createNewArticle() function within our main.go file.

func createNewArticle(w http.ResponseWriter, r *http.Request) {
    // get the body of our POST request
    // return the string response containing the request body    
    reqBody, _ := ioutil.ReadAll(r.Body)
    fmt.Fprintf(w, "%+v", string(reqBody))
}

With this function defined, you can now add the route to the list of routes defined within the handleRequests function. This time however, we’ll be adding .Methods("POST") to the end of our route to specify that we only want to call this function when the incoming request is a HTTP POST request:

func handleRequests() {
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/", homePage)
    myRouter.HandleFunc("/articles", returnAllArticles)
    // NOTE: Ordering is important here! This has to be defined before
    // the other `/article` endpoint. 
    myRouter.HandleFunc("/article", createNewArticle).Methods("POST")
    myRouter.HandleFunc("/article/{id}", returnSingleArticle)
    log.Fatal(http.ListenAndServe(":10000", myRouter))
}

Try running this again and then try submitting a HTTP POST request which contains the following POST body:

{
    "Id": "3", 
    "Title": "Newly Created Post", 
    "desc": "The description for my new post", 
    "content": "my articles content" 
}

Our endpoint will trigger and subsequently echo back whatever value was in the request body.

Now that you have validated your new endpoint is working correctly, let’s update our createNewArticle function so that it unmarshals the JSON in the request body into a new Article struct which can subsequently be appended to our Articles array:

func createNewArticle(w http.ResponseWriter, r *http.Request) {
    // get the body of our POST request
    // unmarshal this into a new Article struct
    // append this to our Articles array.    
    reqBody, _ := ioutil.ReadAll(r.Body)
    var article Article 
    json.Unmarshal(reqBody, &article)
    // update our global Articles array to include
    // our new Article
    Articles = append(Articles, article)

    json.NewEncoder(w).Encode(article)
}

Awesome! If you run this now and send the same POST request to your application, you will see that it echoes back the same JSON format as before, but it also appends the new Article to your Articles array.

Validate this now by hitting the <a href="http://localhost:10000/articles" target="_blank">http://localhost:10000/articles</a>:

http://localhost:10000/articles response

[
    {
        "Id": "1",
        "Title": "Hello",
        "desc": "Article Description",
        "content": "Article Content"
    },
    {
        "Id": "2",
        "Title": "Hello 2",
        "desc": "Article Description",
        "content": "Article Content"
    },
    {
        "Id": "3",
        "Title": "Newly Created Post",
        "desc": "The description for my new post",
        "content": "my articles content"
    }
]

You have now successfully added a Create function to your new REST API!

In the next section of this tutorial, you are going to look at how you can add a new API Endpoint which will allow you to delete Articles.

Deleting Articles

There may be times where you need to delete the data being exposed by your REST API. In order to do this, you need to expose a DELETE endpoint within your API that will take in an identifier and delete whatever is associated with that identifier.

In this section of this tutorial, you are going to be creating another endpoint which receives HTTP DELETE requests and deletes articles if they match the given Id path parameter.

Add a new function to your main.go file which we will call deleteArticle:

func deleteArticle(w http.ResponseWriter, r *http.Request) {
    // once again, we will need to parse the path parameters
    vars := mux.Vars(r)
    // we will need to extract the `id` of the article we
    // wish to delete
    id := vars["id"]

    // we then need to loop through all our articles
    for index, article := range Articles {
        // if our id path parameter matches one of our
        // articles
        if article.Id == id {
            // updates our Articles array to remove the 
            // article
            Articles = append(Articles[:index], Articles[index+1:]...)
        }
    }

}

Once again, you will need to add a route to the handleRequests function which maps to this new deleteArticle function:

func handleRequests() {
    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.HandleFunc("/", homePage)
    myRouter.HandleFunc("/articles", returnAllArticles)
    myRouter.HandleFunc("/article", createNewArticle).Methods("POST")
    // add our new DELETE endpoint here
    myRouter.HandleFunc("/article/{id}", deleteArticle).Methods("DELETE")
    myRouter.HandleFunc("/article/{id}", returnSingleArticle)
    log.Fatal(http.ListenAndServe(":10000", myRouter))
}

Try sending a new HTTP DELETE request to <a href="http://localhost:10000/article/2" target="_blank">http://localhost:10000/article/2</a>. This will delete the second article within your Articles array and when you subsequently hit <a href="http://localhost:10000/articles" target="_blank">http://localhost:10000/articles</a> with a HTTP GET request, you should see it now only contains a single Article.

Note - To keep this simple, we are updating a global variable. However, we aren’t doing any checks to ensure that our code is free of race conditions. In order to make this code thread-safe, I recommend checking out my other tutorial on Go Mutexes## Updating Articles Endpoint

The final endpoint you will need to implement is the Update endpoint. This endpoint will be a HTTP PUT based endpoint and will need to take in an Id path parameter, the same way we have done for our HTTP DELETE endpoint, as well as a JSON request body.

This JSON in the body of the incoming HTTP PUT request will contain the newer version of the article that we want to update.

Challenge

Try create an updateArticle function and corresponding route in the handleRequests function. This will match to PUT requests. Once you have this, implement the updateArticle function so that it parses the HTTP request body, using the same code that you used in your createNewArticle function.

Finally, you will have to loop over the articles in your Articles array and match and subsequently update the article.

Conclusion

This example represents a very simple RESTful API written using Go. In a real project, we’d typically tie this up with a database so that we were returning real values.

#go #rest #api #web-development

What is GEEK

Buddha Community

Creating a Simple RESTful API in Go
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

1602682740

A Simple Guide to Planning API Roadmaps

APIs - the current “big thing” - offer the opportunity for modern organizations to unlock new and lucrative business models. The article below covers some tips on how to spin the API flywheel and leverage its possibilities.

In the API economy, a successful service can gain popularity and be utilized in ways unpredicted and often inconceivable by its original owners. The very flexible nature of the technology opens many doors, including business collaborations, reuse in third-party products or even conquering hardware barriers by reaching a spectrum of devices.

What to consider

Taking the builder’s perspective

Important note: Most of the time API consumers are not the end-users but rather the app developers. Any new venture ought to be supported with excellent learning resources and descriptive documentation. These things combined will ensure a top-notch developer experience and encourage adoption of your product, increasing its visibility in the market.

More than the revenue

While in the simplest scenario, the most popular API business model is revenue via service charges, there are several other goals:

  • **Growth **- APIs are finely-grained and, usually, short-term projects that bring lots of value. Decoupling sectors of your business and encapsulating them in the form of concise, dedicated APIs enable teams to work in parallel, encouraging company growth.
  • **Reach **- By building APIs for wide use, the organization can extend its group of recipients and open new opportunities to cooperate with other players in the market and discover new collaborations.
  • **Compliance **- Products and services implemented as an API ecosystem can freely exchange data between one another, whether they are internal or external.
  • **Insight **- The rate of use of APIs will surely give an idea of what consumers value the most. Also, implementing APIs alone helps to clarify what pieces of your business are crucial. This helps to revise implementation details and encourages reflection of your current technological solutions.

#api #api-development #api-integration #restful-api #api-based-business-model #api-first-development #automation #rest-api

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