If you are starting to develop a Swift app that works with a REST API, you may be overwhelmed thinking about all the code you have to write. What if you forget a data structure? What if you forget to add a property to a data structure? Wouldn’t it be nice to have someone create the Swift code for you?
The command-line app CreateAPI makes this possible. Supply a JSON or YAML file that contains the REST API, and CreateAPI creates a Swift package with Swift code for the REST API. By using CreateAPI you can make faster progress on a Swift app that uses REST APIs.
The CreateAPI GitHub page has installation instructions. You can install it using Homebrew or Mint or by cloning the GitHub repository and installing it from source. Installing from source worked for me.
Generating a Swift Package with CreateAPI
Generating a Swift package with CreateAPI has the following steps:
- Download a JSON or YAML file that contains the REST API.
- Open the Terminal app.
- Navigate to the folder that contains the file.
- Run CreateAPI.
The most common way to run CreateAPI is to run the
create-api generate command with the
--config-option options. The following example demonstrates running CreateAPI:
create-api generate "APIFile.json" --output "./PackageName" --config-option "module=PackageName"
The name of the JSON file must be in quotes. Replace
APIFile.json with the name of the file containing the REST API. Replace
PackageName with the name you want for your Swift package.
The CreateAPI GitHub page has a tutorial that contains more detailed instructions.
CreateAPI is in its early stages of development. It may not work with every REST API. I was unable to generate a Swift package for GitHub’s REST API.
Add the Package to Your Xcode Project
After creating the Swift package you can add it to your project like any other Swift package. If you have never added a Swift package to a project in Xcode, take the following steps:
- Select the project file from the left side of the project window to open the project editor.
- Select the project from the left side of the project editor.
- Click the Package Dependencies button at the top of the project editor to show a list of Swift packages in the project.
- Click the Add button at the bottom of the package list.
- Click the Add Local button in the sheet to add your package.
Import the package module in your source code files, and you can start using the package in your app.
If you want to see an example of a Swift package that CreateAPI creates, I have a package for Jira’s REST API on GitHub.