Table of Contents
- Introduction
- Prerequisites
- Setup
- Building a Basic RESTful API
- Adding CRUD Operations
- Testing the API
- Conclusion
Introduction
In this tutorial, we will learn how to create a RESTful API using Go programming language. By the end of this tutorial, you will be able to build a basic API with CRUD (Create, Read, Update, Delete) operations and test it using tools like cURL or Postman.
We assume that you have some basic knowledge of Go programming language, including concepts like variables, functions, and structs. If you are new to Go, we recommend referring to official Go documentation or other online tutorials to get familiar with the language.
Prerequisites
Before starting this tutorial, make sure you have the following prerequisites:
- Go programming language installed on your machine
- A text editor or an Integrated Development Environment (IDE) for writing Go code
- Basic understanding of RESTful APIs and HTTP methods (GET, POST, PUT, DELETE)
Setup
-
Create a new directory for your project. Open your terminal or command prompt and run the following command:
```bash mkdir my-api && cd my-api ```
-
Inside the
my-api
directory, create a new Go module using the following command:```bash go mod init github.com/your-username/my-api ``` Replace `your-username` with your actual GitHub username or any other username you prefer.
-
Open the project directory in your text editor or IDE.
Building a Basic RESTful API
First, let’s create the basic structure of our RESTful API.
-
Create a new file called
main.go
in your project directory. -
Open
main.go
and add the following code:```go package main import ( "fmt" "log" "net/http" ) func main() { // Define the API routes http.HandleFunc("/", homeHandler) // Start the server log.Fatal(http.ListenAndServe(":8080", nil)) } func homeHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Welcome to my RESTful API!") } ``` In this code, we define a simple HTTP server that listens on port `8080` and maps the root URL ("/") to the `homeHandler` function. The `homeHandler` function writes a welcome message to the response writer.
-
Save the
main.go
file. -
Now, let’s run the API server. In your terminal or command prompt, navigate to the project directory and run the following command:
```bash go run main.go ``` You should see the server starting message without any errors.
-
Open your web browser and visit
http://localhost:8080
. You should see the welcome message displayed on the page.Congratulations! You have successfully created a basic RESTful API with Go.
Adding CRUD Operations
Now, let’s enhance our API by adding CRUD operations for a specific resource, such as a Todo item.
-
Create a new file called
todo.go
in your project directory. -
Open
todo.go
and add the following code:```go package main import "encoding/json" type Todo struct { ID string `json:"id"` Title string `json:"title"` Content string `json:"content"` } var todos []Todo // GET /todos func getAllTodos(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(todos) } // POST /todos func createTodo(w http.ResponseWriter, r *http.Request) { var todo Todo json.NewDecoder(r.Body).Decode(&todo) todos = append(todos, todo) json.NewEncoder(w).Encode(todo) } // DELETE /todos/{id} func deleteTodoByID(w http.ResponseWriter, r *http.Request) { // Extract the {id} parameter from the URL // Perform necessary delete operation // Handle error and success responses } ``` In this code, we define a `Todo` struct representing a Todo item with its properties. We also define an empty slice `todos` to store multiple Todo items. The `getAllTodos` function returns all the Todos as a JSON response. The `createTodo` function creates a new Todo item by decoding the JSON payload from the request body. The `deleteTodoByID` function deletes a Todo item based on the provided ID.
-
Open
main.go
and add the following import statement at the top:```go import ( // Other import statements "github.com/gorilla/mux" ) ``` This import statement is required to use the `gorilla/mux` package which provides a powerful router for building flexible HTTP APIs.
-
Replace the existing
main
function with the following code:```go func main() { // Create a new router router := mux.NewRouter() // Define the API routes router.HandleFunc("/", homeHandler) router.HandleFunc("/todos", getAllTodos).Methods("GET") router.HandleFunc("/todos", createTodo).Methods("POST") router.HandleFunc("/todos/{id}", deleteTodoByID).Methods("DELETE") // Start the server log.Fatal(http.ListenAndServe(":8080", router)) } ``` In this code, we create a new router using `mux.NewRouter()` and replace the previous `http.HandleFunc` calls with `router.HandleFunc` calls to handle the API routes.
-
Save the
main.go
andtodo.go
files. -
Restart the API server by running the following command in your terminal or command prompt:
```bash go run main.go ```
Congratulations! You have added CRUD operations to your RESTful API.
Testing the API
Now, let’s test our API using a tool like cURL or Postman.
-
Open your preferred API testing tool or terminal.
-
Send a GET request to
http://localhost:8080/todos
to retrieve all the Todo items. You should receive an empty JSON array. -
Send a POST request to
http://localhost:8080/todos
with the following JSON payload:```json { "id": "1", "title": "Buy groceries", "content": "Milk, eggs, bread" } ``` You should receive a JSON response containing the created Todo item.
-
Send another GET request to
http://localhost:8080/todos
to retrieve all the Todo items. You should receive an array containing the previously created Todo item. -
Finally, send a DELETE request to
http://localhost:8080/todos/1
to delete the Todo item with ID “1”. You should receive a success response.Congratulations! You have successfully tested your API.
Conclusion
In this tutorial, we have learned how to create a RESTful API using Go. We started by setting up a basic API server and then enhanced it by adding CRUD operations for a Todo resource. We also tested our API using cURL or Postman.
By following this tutorial, you should now have a good understanding of building RESTful APIs with Go. You can further explore and expand your API by adding more resources, implementing additional HTTP methods, and integrating with databases or external services.
Remember to refer to the official Go documentation for more detailed information on Go’s HTTP package and other related topics. Happy coding!