A Massive Guide To Building RESTful API For Your Mobile App Savvy Apps
User Manual:
Open the PDF directly: View PDF .
Page Count: 20
Download | |
Open PDF In Browser | View PDF |
13/06/2018 YOU'RE READING: A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps B LO G O R K a RESTful S E R V API I C Efor S Your A B O U TApp A Massive Guide toWBuilding Mobile BLOG OC NTTA C T C O NCTA Skip to a Section What to Know Before Using This RESTful API Guide A Massive Guide to Building a RESTful API for Your Mobile App 104 How Are Backends for Mobile Apps Shares Di erent? Considerations for Setting Up Your App's RESTful API How to Execute Your RESTful API for Mobile Apps Concluding Note DEVELOPMENT TIPS We build apps of all shapes and sizes here at Savvy Apps, but a common element is that they communicate with servers. Very few apps today operate without some sort of Internet connectivity, meaning that they interact with a backend, web services, or APIs. These APIs could be provided by Google, Amazon, Facebook, or comparable third-parties. They also could be APIs that are developed internally. The problem for these internal or in-house APIs are twofold. Many don't take the time to plan out a good API. Additionally, even with the abundance of apps, not everyone has built https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 1/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps web services YOU'RE READING:or APIs for apps specifically. In our experience, we've found that establishing B LO G C O N TA C T A Massive Guide to Building a RESTful API for Your Mobile App guidelines on how to build better APIs for mobile apps saves time and e ort during development and reduces headache later on in the process. We wrote this guide to outline the best practices for building out APIs, web services, and Skip to a Section databases for mobile apps and mobile clients. In this post, we go in-depth on creating a What to Know Before Using This RESTful API specifically for mobile apps. This information is not only for us at Savvy Apps. RESTful API Guide 104 It's helpful for our customers and any other web or backend development teams who want How Are Backends for Mobile Apps Shares to properly build and maintain their own app-focused backends. Di erent? Considerations for Setting Up Your App's RESTful API TL;DR How to Execute Your RESTful API for Use a well-known architecture so new developers know how it works. Mobile Apps Make the server do the heavy li ing so mobile clients don't have to. Concluding Note Version your API so it handles requests coming in from new and legacy users alike. Account for o line usage and usage across devices. Prioritize performance and scalability when picking where to host your server. Use standard security protocols and well-vetted authentication/encryption libraries. Build three backend environments: development, staging, and production. Let your data decide the type of database you use. Construct API URL endpoints so that it's very clear what that resource contains. For requests, let the client send full objects, and the server use the fields it needs. Utilize UTC for dates/times, and let the client figure out how to display the data. Remember that GET and PUT requests need to be idempotent. What to Know Before Using This RESTful API Guide REST is by far the most commonly-used style for designing APIs, especially in the mobile world. There are also particular subsets of REST, like OData , that further define how data should be transmitted between your apps and the server. While those subsets may be best for your particular needs, we're going to keep the conversation broad enough to cover all REST styles. Adhering to a popular, generic, RESTful architecture style will ensure that new developers tasked with maintaining your server code in the future will be familiar with how it works and, more importantly, how new services should be built onto it. https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 2/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps In this READING: guide, we'll also be discussing RESTful APIs through the lens of mobile app systems. YOU'RE B LO G C O N TA C T A Massive Guide to Building a RESTful help API for Your Mobile Appweb apps and other systems These rules, however, will certainly with supporting with your API too. In most cases, the mobile app client asking for resources and the backend server handing out those resources are going to be written in di erent programming languages and o en by di erent development teams. Adhering to the REST principles laid Skip to a Section out below will ensure that both teams are setting and fulfilling the proper expectations What to Know Before Using This when the time comes for the two platforms to communicate with each other. Nothing is RESTful API Guide 104 worse than thinking that you've completed a new endpoint before realizing it's not in a Shares How Are Backends for Mobile Apps format the mobile client can use e iciently. In projects where Di there erent?are multiple dev team Considerations for Settingthese Up Your members, it is critical for everyone to stay in constant communication regarding RESTful shared blueprints to avoid unexpected miscommunications,App's delays, andAPI wasted time. How to Execute Your RESTful API for Adhering to a commonly-agreed set of standards and expectations will allow teams to Mobile Apps iterate faster and more e iciently, which makes development and maintenance less expensive in the long run. Concluding Note How Are Backends for Mobile Apps Different? Before we dive into the hosting, security, architecture, and other considerations for creating your RESTful API, let's examine what makes building an API for mobile apps di erent from other systems. These mobile-specific concerns are essential to making sure your RESTful API is prepared to work e iciently with a mobile app and the expectations of its users. HTTPS, Not HTTP The internet was built on HTTP, but mobile platforms enforce HTTPS requirements with modern encryption and trusted signed certificates. A mobile backend needs to use HTTPS for every endpoint. Your development, staging, and production environment servers should all be using the same type of signed certificates. This will save you headaches later when migrating/testing features on each environment, allowing you catch security issues upstream before they become a problem on the live server and start a ecting real users. Server Does Most of the Work To save on network data costs and battery life for users, you typically want mobile clients doing as little work as possible. It's quite rare to see a mobile app that couldn't benefit from https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 3/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps querying and storing data remotely or o loading burdensome and sensitive tasks to more YOU'RE READING: B LO G C O N TA C T A Massive Guide to Building a RESTful API for Your Mobile App powerful, remote machines. Plugging into a remote API keeps your stored data secure and allows your app to continue running smoothly for the user, staying focused on presenting your data quickly instead of calculating. Mobile app users expect their data to be synced across all their devices, which is also solved by moving the data o the device with an API. Skip to a Section What to Know Before Using This Letting the server do the heavy li ing also saves time for developers working on multiple RESTful API Guide 104 platforms by moving and consolidating code to your server and presenting the results to Shares How Are Backends for Mobile Apps both your iOS and Android apps. The server is going to haveDiaccess erent?to much better for Setting hardware than the mobile clients for number crunching, so Considerations it is wise to leverage it.Up Your App's RESTful API Server Issues Can Kill an App How to Execute Your RESTful API for Mobile Apps Notewith a You can also expect any errors a mobile user experiences toConcluding be broadcast megaphone. Tech users these days have little patience when something doesn't work as expected, especially mobile app users. There's no bigger stage for issues to be shared than in App Store and Google Play app reviews. If something goes wrong, the server needs to respond with user-friendly error messages or error codes the client can use to assuage the user and, hopefully, help fix the issue. Even a single error can cause a 1-star review and positive reviews are critically linked to the success of an app. Too many negative reviews caused by server issues will stop new downloads for your app. Versioning is More Important With mobile app users updating their apps (or not) at di erent frequencies, versioning your API becomes more important than other, more controlled environments. With several di erent versions of the app running in the wild, the server needs to consolidate and handle the various requests coming in from new and legacy users alike. We'll dig into e ective strategies on how to handle this later. Plan for Push Notifications A useful communication avenue unique to mobile is the push notification . There are third party tools that specialize in push notification, but sometimes you need to manage the process yourself. Your server may be responsible for tracking device tokens that maps devices to users for sending push notifications. Using a service like Firebase, however, to https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 4/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps manage device tokens and send push notifications to iOS and Android users is typically YOU'RE READING: B LO G C O N TA C T A Massive Guide to Building a RESTful API for Your Mobile App more cost e ective than building your own. Reconciling Offline Activity Many mobile users will expect the app to have some limited Skipfunctionality to a Section even while o line. Once reconnected to the server, reconciling the o line activity with the rest ofUsing the database What to Know Before This API Guide needs to be considered. This is especially important for appsRESTful that users can access on 104 How Are Backends for Mobile Apps multiple devices, such as their phone and tablet. Coordinating API calls with timestamps Shares Di erent? and order of operations is something that needs to be discussed by the frontend and backend developers. Considerations for Setting Up Your App's RESTful API How to Execute Your RESTful API for Mobile Apps Considerations for Setting Up Your App's RESTful API Concluding Note Now that we've looked at what sets mobile apart from other systems, we can dive deeper into planning your RESTful API. These tips address common concerns for hosting the server, dealing with security, creating the backend architecture, choosing database and storage options, using the right tools, and supporting multiple platforms. Hosting the Server Choosing the location to host your server is a big decision. If you don't have the desire or capacity to host your own bare-metal server, there are plenty of cloud-hosted solutions available these days. Every project is di erent, each with specific needs for performance, scalability, and administrative features. Some core factors to pay attention to while evaluating services for where to host your server include: How does the service scale its resources? This could be horizontally (adds more machines) or vertically (upgrading hardware resources for existing machines). How will the cost increase with usage? Are there any migration features that would allow you to easily stand up multiple environments (development/staging/production) for your project? What features are already baked into the system that would save you time and energy from trying to recreate? https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 5/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps What steps YOU'RE READING: does the service take to protect your system (i.e. encryption, automated B LO G A Massive Guide to Building a RESTful API for Your Mobile App C O N TA C T back ups, uptime monitoring)? How easy can the data be ported to another service or platform? Protecting the Data Skip to a Section Depending on your needs, you have a wide array of authentication mechanisms to This leverage. What to Know Before Using API Guide Any hosted service you choose should already include easy RESTful integration of HTTPS and 104 How Are Backends for Mobile Apps trusted CA certificates. HTTP Basic Authentication is the easiest to implement, but it's also Shares Di erent? the least secure. OAuth2 is widely accepted as a secure, standard way of performing Considerations for Setting Up Your authentication and is highly recommended. There are plenty of libraries for social logins or App's RESTful API phone number authentication you could use as well. Do notHow try to write your to Execute Your own RESTful API for authentication! There is no need to reinvent the wheel hereMobile whenApps you can rely on existing Concluding protocols and libraries that have already been vetted by many others Note on both client and server side. Protecting each API endpoint behind authentication requirements should be the norm. Don't allow free passes on a resource unless necessary for functionality. Sensitive data should be protected. This is a given, but security is a spectrum, not an absolute. Encrypt your user's sensitive data. Encryption may not be necessary for every project, but it should always be considered. Don't store your passwords in plain text. Please. Not only should you hash passwords, but using random salts for each password will significantly improve security. Planning the Architecture As we already discussed, you're hopefully planning on building not one, but three discrete backend environments : development, staging, and production. The development environment is where frequent development changes are rolled out as they're completed by developers. Data here can be generated by developers; this can be achieved through automated scripts to populate a database with a healthy amount of test data. As code passes through all its tests in continuous integration (hopefully you're testing your server's logic and API endpoints) and gets the OK from QA, it graduates into the staging environment. https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 6/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps The staging environment is going to try to resemble production as much as possible. YOU'RE READING: B LO G C O N TA C T A Massive Guide to is Building a RESTful API for Yourreal/live Mobile App Ideally, data here an import of transformed sampled data stripped of personal information. The more realistic data used here, the better confidence you'll have of how your system will perform in production. Porting data may not be feasible for your project, but having some sort of quasi-representative data in these first environments is critical to Skip to a Section reducing risk and discovering bugs in the logic before becoming a real issue. If the content What to Know Before Using This cannot be reproduced, having at least roughly the same quantity of data you're expecting in RESTful API Guide 104 production in these environments again will pinpoint bottlenecks in the system early. How Are Backends for Mobile Apps Shares Otherwise, irreproducible slow downs, hang ups, and bugs may occur in production that Di erent? can be a nightmare to track down in development. Considerations for Setting Up Your App's RESTful API Making Database and Storage Decisions How to Execute Your RESTful API for Mobile Apps Concluding No matter what type of database you use, it's worth noting that entityNote IDs should be randomly generated UUIDs, not sequential. This helps secure resources by making IDs much harder to guess. When it comes to storing your data, you might be considering a traditional relational database like MySQL or MariaDB. Or maybe you prefer the scalability of a noSQL document database like MongoDB. Or perhaps you prefer the flexibility of a hybrid approach that something like PostgreSQL can o er with both relational or document storage support. Which database your project should use is really going to depend on your data. Here are some notes to cover the basics: MySQL/MariaDB Well established, stable and reliable Lots of libraries, frameworks and tools to leverage Data is rigid, well structured and defined, leading to less data mismatch bugs Scaling requires a lot of domain-specific knowledge MongoDB No tables, no formal schema, non-relational Easier to scale than SQL-based databases Easy ramp up and iteration of database model Easier to shoot yourself in the foot PostgreSQL https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 7/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps Support YOU'RE READING: and popularity is growing rapidly B LO G A Massive Guide to Building a RESTful API for Your Mobile App Built around giving more features and tools for DB admins C O N TA C T Flexible enough to mix relational data with model-independent data Cloud document storage Skip to a Section A cheap solution could be something like using Amazon S3 Buckets for storing large sets of whole documents 104 Shares Finding the Right Tools What to Know Before Using This RESTful API Guide How Are Backends for Mobile Apps Di erent? Considerations for Setting Up Your You're going to need the right tools to get the job done. Whether it's communication App's RESTful API between project teams, current team members, or future team going through the Howmembers to Execute Your RESTful API for Apps on any so ware onboarding process for your project, communication is key Mobile to success Note tool and that all project. During development, make sure you're using a clearConcluding dev-tracking teammates have access. We're fans of Pivotal Tracker and Trello , but any similar tool will work. The point is to keep progress out in the open and maintain a historical record. This is especially important with multiple developers on a project. The developer responsible for writing the code to log in a user in an iOS app will really want to know when the server-side authentication API is ready to consume. They may even have a discussion around shi ing priorities of the server developers to complete that task sooner rather than later if it's blocking the iOS app from progressing further. Letting the whole team have knowledge of not only what's currently being worked on but also what's up next will allow a more fluid workflow of coordinating work schedules to complete tasks in the most e icient way possible. This will also help circumvent issues where the API may have changed prematurely, causing a delay or otherwise negatively impacting development in the mobile app. It's also worth noting that just like any so ware iteration, release notes are invaluable when a new API is deployed, even during development. When done right, RESTful API endpoints should be easy to test and should have tests covering both obvious use cases as well as expected edge cases for each endpoint. One of the core principles of REST is stateless, which makes our API endpoints small, modular black boxes, ripe for testing. New data comes in, successful message comes out, and the newly persisted data changes are easily verifiable in the database. Request for data goes in, https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 8/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps expected data response comes out. The testing framework to use will of course depend on YOU'RE READING: B LO G C O N TA C T A Massive Guide to Building a RESTful API for Your Mobile App the language you're writing the backend server logic in. No matter how you write your tests, they should be well-maintained and run with 100% passing rate before every deploy. During development, your testing suite may prove su icient documentation for other Skip to a Section developers to review how the system works. Eventually you'll need to write down, in plain What to Know Before Using This english, how the system you built actually works. I know this is the least favorite part for RESTful API Guide 104 most of us, but it is critical for the success of a project in the long term. Your documentation How Are Backends for Mobile Apps Shares is only as good as the e ort you put into it. Fortunately, these Di days erent?there are documentation Considerations for documentation Setting Up Your tools out there that can do a lot of the work for you. One of our favorite API App's RESTful tools is Postman . Not only is it useful for exploring or testing an API, butAPI it can help How to Execute Your RESTful API for generate all the requests, responses, and handled error codes and store them for you to Mobile Apps reference later. You can literally build your documentation as you build an integration test suite for your new API. Concluding Note No matter how you document your API, try to include successful response codes, sample requests, and examples of both successful and failed responses, with expected error codes and messages. You also need to make sure this documentation is accessible to everyone on the team. It does no good if no one else can read it! Included below are some other documentation tools you may want to look at: Swagger Can support bottom up or top down (contracts first, then write code) Language neutral, but does support a large variety of languages via plugins Apiary Built on top of open sourced API Blueprint Slate Supports Markdown Can be hosted on Github Supporting Multiple Platforms https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 9/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps If you're building an API for a mobile app to consume, chances are good that you'll need to YOU'RE READING: B LO G C O N TA C T A Massiveother Guideplatforms to Building RESTful APIThe for general Your Mobile support inathe future. ruleApp of thumb for building APIs for mobile is to make the client as dumb and thin as possible, while keeping all the heavy sorting, filtering, number crunching, data aggregating, and consolidation on the server. This leverages the more powerful hardware of the server and tries to keep the client logic simple Skip to a Section while fetching and showing the data to the user as quickly as possible. What to Know Before Using This RESTful API Guide 104 This is important because when you're building your app on iOS, Android, and web, you How Are Backends for Mobile Apps Shares don't want to rewrite complicated filtering and parsing logicDithree times if you can avoid it. erent? For this reason, you'll want to allow robust sorting and filtering Considerations options, letting for Setting theUpclient Your App's API and force the fetch only what it needs. For example, don't return everything in RESTful a collection How to Execute Your RESTful API for client app to sort through the data to find what it was looking for. Use pagination of long Mobile Apps lists of data to avoid overwhelming both the client and the user and allow the client to Concluding Note determine how many results it should get back. While supporting multiple platforms, it may be beneficial to capture device names, OS versions, and types in request headers since those can be useful while reading logs and debugging in the future. How to Execute Your RESTful API for Mobile Apps Now that we've discussed how and where you should set up your server, let's dig into how to actually design your API in a RESTful manner. This section runs through how to use proper url paths, requests and responses, and other guidelines for implementing your RESTful API. Handling URL Paths For the rest of this guide, we're going to assume we're building an API for a library. For example, some of your resources might be a book, a book club, an author, a user, or a library location. The client would want access to all of those resources via the API so you could construct some endpoints mapping to: GET POST GET PUT PATCH DELETE /books /books /books/{bookId} /books/{bookId} /books/{bookId} /books/{bookId} https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 10/20 13/06/2018 GET A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps /books/{bookId}/authors YOU'RE GET READING: /bookClubs/book B LO G C O N TA C T A Massive Guide to Building a RESTful API for Your Mobile App GET /users/{userId} GET /users/{userId}/favoriteBooks Notice the pattern emerging. We hope to construct our API URL endpoints in a way that makes it very clear what that resource contains. Now let's talk about the two useful RESTful Skip to a Section design tools: nouns and verbs. The actions GET, POST, PUT, PATCH, DELETE areUsing the This verbs, What to Know Before meaning they are the HTTP methods telling the server whatRESTful actionAPI to Guide perform. The URL 104 Are acted Backends Mobile Apps path itself tells you the nouns, which are the resources that How will be on.for It's important Shares Di erent? to make this distinction here, because otherwise you could end up with a messy API that's di icult to follow. Now take a look at these (bad) endpoints: Considerations for Setting Up Your App's RESTful API How to Execute Your RESTful API for Mobile Apps Concluding Note /getBooks /createNewBook /checkOutBook/{bookId} /returnBook/{bookId} /addBookToFavorites /addNewMemberToBookClub /changeBookClubMeetingTime /changeBookClubMeetingLocation /removeBookClubMember You may glean more about what those API endpoints might be trying to do at a glance, but now you're going to have to add a new API endpoint for every possible action on that resource. Doing so will lead to frustration for the clients trying to consume your API. You want to keep your API concise and modular. You're not only creating an API for your apps right now, but you also need to think about how additional features or data types will fit into the API. To improve your API's robustness, just let the requests drive the server's response. Now this may seem like a silly statement, because of course a client will make a request and the server's job is to send a response. If the server is dictating what, how, and where a client can fetch or change data, then that means that every time they want to perform a new action or feature, the client developers are going to have to wait for changes to be made to the server. The server is allowed to refuse requests. That's what error messages are for. But by building https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 11/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps your YOU'REendpoints READING: with nouns and reacting to the data in the request, you'll provide a stable B LO G C O N TA C T A Massive Guide to Building a RESTful APIover for Your API that will require less maintenance timeMobile as youApp allow clients to do more with less. Now, just because we're using nouns to drive the URLs, doesn't mean our resources need to be the same as our data model objects. The URL should include model objects where Skip to a Section appropriate, but we want to make these paths easy to read and intuitive. For example, the What to Know Before Using This resource /favoriteBooks probably will just return the same objects as /books, but we RESTful API Guide 104 provide the clarification of what type of books we're going to get back. This separation also How Are Backends for Mobile Apps Shares allows you move the logic of finding, filtering, and calculating to the Di favoriteBooks erent? server, again allowing the mobile client to remain thin and focused on pulling the Up needed Considerations for Setting Your data and presenting it to the user. App's RESTful API How to Execute Your RESTful API for Mobile Apps This leads directly into how to handle filtering, sorting, pagination, and searching. These Concluding Note four sub-actions are all related as they let the client declare what resources it's looking to retrieve from the server. Again, we want to construct our APIs to give the clients as much freedom as possible here, without having to exert too much extra e ort on our side. We handle filtering, sorting, pagination, and searching with URL parameters. This allows us to keep our API endpoint quantity low and manageable while giving the clients the tools they need to perform more complicated actions. Once we add the ability to handle these types of query parameters, we open up the door for the client to make changes to better serve up content to the users as they see fit. Today, maybe they want to show all libraries in alphabetical order, but tomorrow they realize that sorting them by geographical location is more useful to end users. Or maybe they want to let end users choose how they want to see libraries sorted as a configurable setting. The client can do all of that without any extra work on the server side, which is what we want. Here are some examples of handling these URL parameters for our library API: GET GET GET /libraries?sortBy=name&isCurrentlyOpen=true&pageCount=10 /books?queryTitle=Sherlock+Holmes&queryAuthor=Arthur+Conan+Doyle /bookClubs?genre=mystery API versioning is another feature we should implement to achieve the robustness that is especially important for mobile apps. Mobile developers don't always have the luxury of forcing so ware updates for all end users, so our API is going to have to be able to handle https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 12/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps both and new requests. We'll do this by routing requests with a version number. Some YOU'REold READING: B LO G C O N TA C T A Massive to Building RESTful should API for Your App will argueGuide that this versionanumber go inMobile the URL path, and some will argue it should be placed in the request header. We prefer it to be in the URL path for easier discovery, but that's up to you and your team to discuss. We treat versioned resources as di erent resources, and that's why we think they deserve a unique path rather than a request header to a Section value. Either way, the benefit of versioning API is allowingSkip newer features to be requested while not interfering with legacy requests. 104 RESTful API Guide How Are Backends for Mobile Apps Shares GET GET What to Know Before Using This /v1/books /v2/books Di erent? Considerations for Setting Up Your App's RESTful API How to Execute Your API for Another important guideline to call out with all of our URL examples above isRESTful that they read Mobile traverse Apps from le to right, from broad to specific. You're letting the clients a tree of API Concluding Note endpoints, starting with the root single point of entry, where they can request anything, and letting related resources cascade from there. Again, the aim is to make these APIs easily explorable and intuitive for the clients to navigate. Determining what resources to actually expose in your API is going to be up to you and your dev team to decide. If you have any UI or UX designs for how the client apps are going to work, it's important for the developers working on the backend to be aware of what data they clients will need and when. Ask yourself questions like: Does a user need to log in to see this resource, or is it public? Does a user need to choose a library or city before viewing book clubs, or are they not attached to a particular location? What actions does the UI allow when viewing the details of a particular book, and how can we design the API to allow the client to best perform those actions?” Rules for Requests and Responses So we've laid out how we'll construct our API endpoints, now let's talk about how to communicate e ectively within each of those endpoints. Let's start with the request. When handling a request, don't force the client to only send one or two fields. Allow them to send full objects if they wish, while the server just uses the fields it needs. If a request does come in with only a few fields, don't assume the missing fields are null. Fields that are null should be stated explicitly in both requests and responses. This prevents the other end https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 13/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps from to guess if the data really is null or just not included. Take a look at the YOU'REhaving READING: B LO G C O N TA C T A Massivebelow: Guide to Building a RESTful API for Your Mobile App example PATCH /books/123 Skip to a Section { 104} "author": "Arthur Conan Doyle" "publicationYear": "1902" Shares What to Know Before Using This RESTful API Guide How Are Backends for Mobile Apps Di erent? Considerations for Setting Up Yourthe While this is not a complete book object, we'll build the server robust enough to handle RESTful API resource with important information. Here the client had made it clear to App's update the book How to Execute Your RESTful API for id 123, as told by the URL. The request body tells us this book should change its author and Mobile Apps publication year. Only these fields should be updated because it is a PATCH request. The Concluding Note other details are not important to this request, and therefore not included. This does not mean the title of the book should be set to null, it should just remain untouched. Allowing these partial object requests reduces parsing and handling of extraneous duplicate data. Pay attention to the Content-Type and Accept headers in the request. They'll likely remain application/json for most requests, but if you need to support xml, this is the place to do so (not in the URL!). Other types of resources like files, images, audio, etc. should have their content type set and respected here as well. A er handling the request, we need to send a response. Things might not have gone the way the client expected and an error will need to be returned. Or maybe the request was processed successfully and simply doesn't require any data returned back. Or maybe everything went exactly as expected. This is where the response HTTP status code helps us out. Be deliberate with what status code is returned, with 200, 201, and 204 for successful responses, and 4XX codes for errors. You can bet the clients will be paying attention to these codes, so we need to be careful with what we send back with our response. In every response though, we need to remain consistent. We should not be mixing “camelCase” and “snake_case” for our JSON keys. The norm is camelCase, but an argument could be made for snake_case being more legible. Whatever you choose, use it everywhere. Also, be https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 14/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps consistent with what you name the fields across endpoints. Make sure you don't use a mix YOU'RE READING: B LO G C O N TA C T A Guide to Building a RESTful API for Your Mobile App ofMassive isbn, ISBN, isbnNumber, internationalStandardBookNumber when talking about a book's ISBN. Pick one and use that key everywhere you need to pass that value. When sending responses that could have one or many objects, don't mix sending one Skip to a Section object versus an array. If the client is requesting a collection where you find only one object, What to Know Before Using This put it in an array and return it that way all the time. Handling one object versus many is RESTful API Guide 104 di erent for every programming language, but if you just stay consistent, no time is wasted Shares trying to parse special cases on any platform. How Are Backends for Mobile Apps Di erent? Considerations for Setting Up Your App's RESTful The flip side of this advice is don't wrap your responses or requests in anAPI envelope field to Execute Your RESTful API for unless it provides value. Wrapping an object in a “data” :How {...} will just waste data Mobile Apps and time. As a follow up, don't include metadata on the object that wasn't requested either. Concluding Note Ideally, we want the data model of the server and client to be as close as possible, so throwing in extra fields that aren't part of the requested object will just get in the way. Below are some examples of what not to put in your responses: Don't wrap data with useless envelopes. GET /authors?genre=mystery { "data": { [{ "authorName": "Arthur Conan Doyle", ... }] } } Don't return a single object when the client should expect a collection. GET /authors?genre=mystery { "authorName": "Arthur Conan Doyle", ... } Don't include metadata that isn't relevant to the client requested data. https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 15/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps YOU'RE GET READING: /authors?genre=mystery B LO G C O N TA C T A Massive Guide to Building a RESTful API for Your Mobile App { "requestInfo": { "genre": "mystery" }, [{ "authorName": "Arthur Conan Doyle", ... }] } Skip to a Section What to Know Before Using This RESTful API Guide 104 How Are Backends for Mobile Apps Shares When dealing with dates and times, remember that consistency is key. Accept and send all Di erent? dates in ISO 8601 format with UTC values. Don't let the server pick the time zone, or Considerations for Setting Upthe Your App'sneeds; RESTful the API client mobile display format, or determine what precision the date-time data Execute Your RESTful API for apps will figure out how best to display the date and time toHow thetouser. Mobile Apps Concluding Note Aside from reading a request and creating or finding its response, the server is probably going to need some programmed logic to best execute each request. We need to keep in mind when writing this logic that GET and PUT requests need to be idempotent. This means that no matter how many times a client might call GET /books on our server, the data will remain unchanged. We should avoid doing anything “extra” or behind the scenes that a client might not expect. Whatever logic or indirect actions the server needs to execute in response to a request needs to be communicated and documented to avoid surprises later. Concluding Note Hopefully, this guide has been insightful. When designing and creating our own backends, we focus on placing resources in a modular, explorable, and extendible way and communicating our decisions and priorities e ectively. Constant collaboration between developers working on the client apps and backend also ensures that road blocks can be avoided and continual progress is achieved . The less time we spend guessing how the API is going to work in every situation, the more time we can spend building out the awesome features that make our apps unique . Join 20,000+ Other Readers https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 16/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps YOU'RE READING: Sign up to be notified of new blog posts and be the first to B LO G helpful appYour goodies fromApp Savvy Apps! A Massive Guide to Buildingreceive a RESTful API for Mobile C O N TA C T SEND Skip to a Section Email What to Know Before Using This RESTful API Guide 104 How Are Backends for Mobile Apps Shares Di erent? Considerations for Setting Up Your App's RESTful API BY: MATT TEA JULY 19, 2017 How to Execute Your RESTful API for Mobile Apps Concluding Note Matthew Tea is a developer with a passion for quality, tested code. He's a team player with a strong desire to learn new and upcoming technologies. RECOMMENDED ARTICLES Can Core ML in iOS Really Do Hot Dog Beyond Constraints: Cra ing Advanced iOS Detection Without Server-side Processing? Animations with Auto Layout Machine learning has quickly become an important bedrock for a variety of applications. How we think about design at Savvy Apps encouraged us to develop a new animation https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 17/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps Its mobile implementation, however, has been technique that mixes old-school view YOU'RE READING: B LO G O N TA C T out of reachGuide for many in... technique... A Massive to Building a RESTful API for Your animations Mobile Appwith Auto Layout. Our C Keep Reading Keep Reading Skip to a Section What to Know Before Using This 104 Shares RESTful API Guide How Are Backends for Mobile Apps Di erent? Considerations for Setting Up Your App's RESTful API How to Start Android Development with an iOS Background How toLinking Execute Your RESTful API for How to Use Deep in Your Mobile Mobile Apps App If all you've ever done in the past is iOS development, looking to build an app on Android might make you feel like you're entering... What is deep linking? Deep linking enables app creators to drive user engagement and simplify the app onboarding process. It’s useful in tracking referrals and... Keep Reading Keep Reading Concluding Note RECENT ARTICLES Building a Real-World Web App With Vue.js and Firebase Jeremy Olson Talks About Success in the Evolving App Store Using Advanced Auto Layout Techniques to Adapt Interfaces to Screen and Content 10 App Marketing Tips to Boost Your App's Launch Success Choosing a Firebase Database For Your App: Realtime Database vs. Cloud Firestore https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 18/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps YOU'RE READING: B LO G ToggleButtonLayout: Easily Create C O NToggle TA C T Buttons for Your Android App A Massive Guide to Building a RESTful API for Your Mobile App The Definitive Guide to Expanding Your Native App to the Web Skip to a Section WhatoftoBranding Know Before The Importance forUsing AppsThis RESTful API Guide 104 How Are Backends for Mobile Apps Shares Di erent? Considerations for Setting Up Your App's RESTful API How to Execute Your RESTful API for Mobile Apps Let's Talk Concluding Note YOU MADE IT THIS FAR SO... Want to work with us? LINKS CONTACT Savvy Apps is a Washington, D.C. Careers mobile design and mobile Support development company serving global Privacy Policy 1850 Centennial Park Drive Suite 100 Reston, Virginia 20191 brands and cutting-edge startups. We're a product team for hire that's Terms driven by making life better, one app at (703) 5449191 a time. JUST SAY HI OR See It On a Map REQUEST A QUOTE https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 19/20 13/06/2018 A Massive Guide to Building a RESTful API for Your Mobile App | Savvy Apps YOU'RE READING:Savvy Apps, LLC All Rights Reserved © 2009-2018 B LO G A Massive Guide to Building a RESTful API for Your Mobile App C O N TA C T Skip to a Section What to Know Before Using This 104 Shares RESTful API Guide How Are Backends for Mobile Apps Di erent? Considerations for Setting Up Your App's RESTful API How to Execute Your RESTful API for Mobile Apps Concluding Note https://savvyapps.com/blog/how-to-build-restful-api-mobile-app 20/20
Source Exif Data:
File Type : PDF File Type Extension : pdf MIME Type : application/pdf PDF Version : 1.4 Linearized : No Page Count : 20 Creator : Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.17 Safari/537.36 Producer : Skia/PDF m68 Create Date : 2018:06:13 18:24:46+00:00 Modify Date : 2018:06:13 18:24:46+00:00EXIF Metadata provided by EXIF.tools